本文介绍了有没有办法在Java中覆盖类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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将打印dad。有没有办法让它打印儿子?

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中覆盖类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:07