gpt4 book ai didi

java - 继承 :hidden variable of superclass in subclass

转载 作者:行者123 更新时间:2023-11-29 03:22:03 24 4
gpt4 key购买 nike

考虑以下代码:

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?
}

}

我应该如何在子类中揭示父类(super class)的隐藏变量?

最佳答案

您可以使用 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
}
}

关于java - 继承 :hidden variable of superclass in subclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23035218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com