package Bean;
public class Student extends Person {
public String branch;
public int student_id;
public Student(String name, int age, String branch, int student_id) {
super(name, age);
this.branch = branch;
this.student_id = student_id;
}
public void displayStudent() {
System.out.println("Data of student class:");
System.out.println("Name :" + super.name);
System.out.println("Age:" + super.age);
System.out.println("branch:" + this.branch);
System.out.println("branch:" + this.student_id);
}
public static void main(String[] args) {
Person person = new Student("Kris", 25, "IT", 1250);
// 调用Person类中的displayPerson方法成功,因为当前的变量的引用类型是Person,也就是数据类型的类是Person
person.displayPerson();
System.out.println("");
// person变量调用displayStudent方法失败,因为person尽管存储的是Student对象,但是该变量的引用类型是父类Person,所以不能调用子类的方法,尽管它保存的是子类的对象
// person.displayStudent();
// 如果子类对象保存在父类引用中却像调用子类自己的方法,这个时候可以通过类型强制转换将父类引用的变量强制转换为子类类型的变量,然后就可以调用子类的方法
((Student) person).displayStudent();
}
}
在Java中为什么把子类对象分配给父类引用?
最新推荐文章于 2023-08-25 08:21:50 发布