【问题标题】:Inheritance :hidden variable of superclass in subclass继承:子类中超类的隐藏变量
【发布时间】:2014-04-12 19:39:16
【问题描述】:

考虑以下代码:

class B
{
     int j=15;
}

public class A extends B
{
  int j=10;

  public static void main(String[] args)
  {
      A obj =new A();
      System.out.println(obj.j);   // i now want to print j of class B which is hidden,how?
  }

}

我应该如何在子类中揭示超类的隐藏变量?

【问题讨论】:

  • 认为这是一种糟糕的做法。

标签: java class inheritance subclass superclass


【解决方案1】:

您可以使用super 访问它:

System.out.println(super.j);

但你可以在A 类中使用super,所以你可以这样做:

public class A extends B
{
    int j = 10;

    public void print()
    {
        System.out.println(super.j);
    }

    public static void main(String[] args)
    {
        A obj = new A();
        System.out.println(obj.j); // 10
        obj.print(); // 15
    }
}

【讨论】:

    【解决方案2】:

    您可以使用 super 从 A 类中获取它。您需要为此创建一个方法。示例:

    class A extends B
    {
        int j=10;
    
        int getSuperJ() {
            return super.j;
        }
    
        public static void main(String[] args)
        {
            A obj =new A();
            System.out.println(obj.j);   //10
            System.out.println(obj.getSuperJ());  //15
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 2018-11-15
      • 1970-01-01
      相关资源
      最近更新 更多