【发布时间】:2020-06-07 02:27:17
【问题描述】:
当我创建一个带有父引用的子对象时,像这样Parent p = new Child();
那么基本上它是一个具有父引用和父子属性的子对象。
那么如果它是一个带有父类型引用的子对象,那么为什么我不能用它访问子属性。
我正在尝试做以下事情:
class Parent {
}
class Child extends Parent {
int a = 20;
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.a); //gives compile time error
// question is , p is parent type reference variable , but it is pointing to object of child
// class, then we should be able to access child properties from it, but we cant, why ?
}
【问题讨论】:
标签: java