父类 Person
public class Person {
private int id; public Person(int id) { this.id = id;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String toString() {
return "id="+this.id;
}
}子类 Student
public class Student extends Person{
private String school;
public Student(int id, String school) {
super(id);
this.school = school;
} public String getSchool() {
return school;
} public void setSchool(String school) {
this.school = school;
} public String toString() {
return "id="+this.getId()+" school="+this.school;
}}测试用的
public class test {
public static void main(String[] args) {
Person p1 = new Person(5);
p1 = new Student(2,"aaa");
System.out.println(p1.toString());
}}
我想问的是
Person p1 = new Person(5); 是 生成一个引用 指向 一个PERSON 对象
p1 = new Student(2,"aaa"); 把引用 指向 一个STUDENT 对象
我这样理解有问题吗 ?
然后 为什么 p1只有 PERSON 方法和属性
而p1.toString() 显示 出来 却是 STUDENT 中的 方法
希望 帮我解释下!
public class Person {
private int id; public Person(int id) { this.id = id;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String toString() {
return "id="+this.id;
}
}子类 Student
public class Student extends Person{
private String school;
public Student(int id, String school) {
super(id);
this.school = school;
} public String getSchool() {
return school;
} public void setSchool(String school) {
this.school = school;
} public String toString() {
return "id="+this.getId()+" school="+this.school;
}}测试用的
public class test {
public static void main(String[] args) {
Person p1 = new Person(5);
p1 = new Student(2,"aaa");
System.out.println(p1.toString());
}}
我想问的是
Person p1 = new Person(5); 是 生成一个引用 指向 一个PERSON 对象
p1 = new Student(2,"aaa"); 把引用 指向 一个STUDENT 对象
我这样理解有问题吗 ?
然后 为什么 p1只有 PERSON 方法和属性
而p1.toString() 显示 出来 却是 STUDENT 中的 方法
希望 帮我解释下!
1,Person p1 = new Person(5); 是 生成一个引用 指向 一个PERSON 对象
p1 = new Student(2,"aaa"); 把引用 指向 一个STUDENT 对象
我这样理解有问题吗 ?
解释:p1 = new Student(2,"aaa"); 是父类的引用指向子类对象,你那话没错。
2,然后 为什么 p1只有 PERSON 方法和属性
而p1.toString() 显示 出来 却是 STUDENT 中的 方法
解释:正如上面所说,此时的p1所指向的真实对象就是STUDENT对象。当然要显示STUDENT的方法,若想调用父类的toString()方法,应该结合super.toString(),这是java的多态,要注意与c++里的多态的区别,在c++里面要将方法定义为虚函数,才能实现多态的调用。