public class A
{
public static int i;
}
public class B extends A
{
public static void main(String[] args)
{
System.out.println("print i=" + B.i); // referred to A.i
}
}
我的问题是B.i
如何引用A.i
?
如果静态变量i
是继承的,为什么java还允许在B类中定义另一个变量i
?
最佳答案
A
的公共(public)或 protected 成员在 A
的所有子类中都是可见的。
If the static variable i is inherited why java allows to define another variable i in B class also?
很难推测原因。一个可能的原因是,这允许将成员添加到基类中,而不会破坏任何已经拥有同名成员的派生类。
请注意,如果您在B
中定义另一个i
,它将遮蔽A.i
,从而使其变得困难访问后者。 I've seen people expecting this to behave polymorphically ,但事实并非如此(无论如何,您的情况略有不同,因为 A.i
是 static
)。
关于java - 继承中的静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15922260/