问题描述
class Dad
{
protected static String me = "dad";
public void printMe()
{
System.out.println(me);
}
}
class Son extends Dad
{
protected static String me = "son";
}
public void doIt()
{
new Son().printMe();
}
函数 doIt 将打印爸爸".有没有办法让它打印儿子"?
The function doIt will print "dad". Is there a way to make it print "son"?
推荐答案
是的.但是就变量而言,它被覆盖(为变量赋予新值.为函数赋予新定义是覆盖).只是不要声明变量,而是在构造函数或静态块中初始化(更改).
Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.
在父类的块中使用时会反映该值
The value will get reflected when using in the blocks of parent class
如果变量是静态的,则在初始化过程中使用静态块更改值,
if the variable is static then change the value during initialization itself with static block,
class Son extends Dad {
static {
me = "son";
}
}
或者改变构造函数.
您也可以稍后在任何块中更改该值.它将反映在超类中
You can also change the value later in any blocks. It will get reflected in super class
这篇关于有没有办法覆盖 Java 中的类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!