当我创建带有父级引用的子对象时,像这样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 ?
}
问题是Child
类没有继承Parent
类。您需要执行以下操作:
class Child extends Parent{
....