java的对象数据转给另外一个对象
时间: 2024-05-04 09:18:36 浏览: 15
Java对象之间的数据传递可以通过以下方法实现:
1. 构造函数:在目标对象中定义一个构造函数,该构造函数接收要传递的对象作为参数,并将参数中的属性值赋值给目标对象的对应属性。
2. Setter方法:在目标对象中定义一个Setter方法,该方法接收要传递的对象作为参数,并将参数中的属性值赋值给目标对象的对应属性。
例如,假设有两个对象Person和Student,其中Student是Person的子类,代码如下:
```
public class Person{
private String name;
private int age;
//构造函数
public Person(String name, int age){
this.name = name;
this.age = age;
}
//Getter和Setter方法
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
public class Student extends Person{
private String school;
//构造函数
public Student(String name, int age, String school){
super(name, age);
this.school = school;
}
//Getter和Setter方法
public String getSchool(){
return school;
}
public void setSchool(String school){
this.school = school;
}
}
```
现在需要将一个Person对象的属性值传递给一个Student对象,可以通过以下方式实现:
```
Person person = new Person("Tom", 20);
Student student = new Student(person.getName(), person.getAge(), "Harvard");
```
这里通过调用Student类的构造函数,将person对象的name和age属性值传递给了student对象,并设置了school属性值为"Harvard"。也可以通过调用Student类的Setter方法,将person对象的属性值传递给student对象,例如:
```
Person person = new Person("Tom", 20);
Student student = new Student();
student.setName(person.getName());
student.setAge(person.getAge());
student.setSchool("Harvard");
```