【问题标题】:Accessing child properties from parent type reference in java从java中的父类型引用访问子属性
【发布时间】: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


【解决方案1】:

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

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。因此,最好通过instanceof 运算符检查p 是否为子对象

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

【讨论】:

    【解决方案2】:

    它不起作用的原因是父类无权访问其子类的属性。您可能正在创建一个Child 类,但您将它分配给Parent 对象。由于Child 继承自Parent,您可以将Child 转换为Parent

    你基本上是在做:

     Parent p = (Parent) new Child();
    

    换句话说,您正在创建一个Parent 对象。 Parent 类中没有 a 属性。

    你可以这样做:

    class Parent{
        int a = 20;
    }
    
    class Child extends Parent{
    
    public static void main(String[] args){
         Child c = new Child();
         System.out.println(c.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 ?
    }
    

    【讨论】:

      【解决方案3】:

      这里当你写Parent p = new Child()时,子类的对象是用父类和子类的属性创建的,但是用来保存这个对象的引用变量是父类或者你可以说是父类。

      当我们想要访问任何类的实例方法或变量时,引用变量应该只属于该类或其子类。

      所以我们不能用父类的引用变量来访问子类的变量。 只有父类中存在的变量可以通过父类的引用变量来访问,不管你是用那个引用变量来保存父类对象还是子类对象。

      因此,从 p 引用变量访问代码中的“a”实例变量的唯一方法是将 p 类型转换为 Child 类型,然后它可以访问 Child 类的变量。

      `
      Parent p = new Child();
        System.out.println(((Child)p).a);
      

      `

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多