从java中的父类型对象访问子属性

问题描述 投票:0回答:1

当我创建带有父级引用的子对象时,像这样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
1个回答
0
投票

问题是Child类没有继承Parent类。您需要执行以下操作:

class Child extends Parent{
    ....
© www.soinside.com 2019 - 2024. All rights reserved.