【问题标题】:subclass object accessing superclass hidden variable [duplicate]访问超类隐藏变量的子类对象
【发布时间】:2015-05-23 05:52:30
【问题描述】:

我有一个子类对象。我可以在不使用 super 关键字的情况下访问超类的隐藏变量吗? ??实际上,我找到了一种技术..它的工作原理,但我不明白它背后的概念原因。

class A {
    public int a = 5; 
    private int c = 6; 

    void superclass() {
        System.out.println("Super class" + " " + "value of a is " + a);
        System.out.println("Super class" + " " + "value of c is " + c);
    }
}

class B extends A {
   int b = 7;
   int a = 8; 

   void subclass() {
       System.out.println("Sub class" + " " + "value of b is " + b);
       System.out.println("Sub class" + " " + "value of a is " + a);
   }
}

class Demo {
    public static void main(String args[]) {
       A a1 = new A();
       B b1 = new B();

       b1.superclass();
   }
}

在上面的代码中,如果b1是B类的一个对象,我调用了一个名为superclass()的超类方法;现在输出是a=5。但我的论点是为什么不能是 a=8a=5 是隐藏的,要访问它,我们必须使用 super 关键字。但是在这里没有超级关键字我得到a=5。怎么可能?

【问题讨论】:

  • 你的代码能编译吗?我投票结束这个问题作为题外话。
  • 我不这么认为。我感觉他抄错了两行。我已经编辑了这个问题,一旦获得批准,它将更具可读性。 @ChetanKinger,旁注,我不觉得这是题外话。
  • @AnindyaDutta 代码无法编译。请阅读this
  • @ChetanKinger 现在可以了 :)
  • @AnindyaDutta 你只是鼓励更多的人变得懒惰并在这个美妙的网站上制造更多的混乱;)。

标签: java inheritance


【解决方案1】:

字段不会被覆盖。

因此,即使B 定义了一个名为“a”的intA 定义了同一个名称的int,但这并不意味着它们是同一个字段。

这里看到的是Encapsulation。通过受控方法访问字段(此处为superclass())。当您调用superclass 时,它会查找字段a,该字段位于其自己的类中。 A 类对 B 中的 a 字段一无所知,甚至不知道它存在。

这里还有另一个 SnackOverflow 问题:If you override a field in a subclass of a class, the subclass has two fields with the same name(and different type)?

【讨论】:

  • 这是否意味着B类的对象确实有父类的私有变量的字段?
【解决方案2】:

在这种情况下,当您调用超类的方法时,无论extends 是哪个类,它都会打印class 中的值。这是因为超类不知道哪个(或多少个类)扩展了它。这就是encapsulation的基本OOP原理。

【讨论】:

  • Java 没有functions
  • methods。很抱歉这个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 2017-09-13
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
相关资源
最近更新 更多