简体   繁体   English

从Java中的超类引用子类

[英]Referencing subclasses from superclasses in java

Suppose I have an abstract class Person . 假设我有一个抽象类Person There is another class Student which extends Person . 还有另一个班级的学生扩展了Person But the Student class has a member variable, say college of type String , which is not there in Person class. 但是Student类具有一个成员变量,例如类型为String的 college ,在Person类中不存在。

We know that we can reference a subclass from a superclass, for example, 我们知道我们可以引用超类的子类,例如,

Person p = new Student(); 人p =新的Student();

Will the object p have the member college ? 对象p会有会员学院吗?

You won't be able to do p.college . 您将无法进行p.college However, you can cast it to Student and in this case it will have: 但是,您可以将其转换为Student ,在这种情况下,它将具有:

((Student) p).college;

In your sample, Person object IS a Student and hence will have the college member. 在您的示例中,“ Person对象是“ Student ,因此将拥有该college成员。

Since you cast the Student to a Person , any public routines or data not present in Person will be hidden by the cast assignment though. 由于您将Student转换为Person ,因此 强制转换 分配会隐藏Person不存在的任何公共例程或数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM