首页 > 解决方案 > 从java中的父类型引用访问子属性

问题描述

当我像这样创建具有父引用的子对象时,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

解决方案


您可以通过对子类型的引用进行类型转换来做到这一点。

class Parent {
}

class Child extends Parent {
    int a = 20;
    public static void main(String[] args) {
        Parent p = new Child();
        System.out.println(((Child)p).a);
    }
}

p如果不是子类型的对象,它将抛出 ClassCastException 。因此,最好 通过运算符检查它p是否是 Child 的对象instanceof

    if (p instancof Child) {
        System.out.println(((Child)p).a);
    }

推荐阅读