Java子类中的静态变量 [英] static variable in subclass Java

查看:59
本文介绍了Java子类中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个与对象无关但与类本身无关的静态变量.但是,该变量也不得与父类或扩展同一父类的所有其他子类相关.

I need to have a static variable that is not related to an object, but to the class itself. However, the variable must also not be related to the parent class, or all other sub-classes that extends the same parent class.

让我们说:

    class Army{
      static int attack = 0;
    }

    class Warrior extends Army{
      public Warrior(){ 
        attack = 50;   // every Warrior object will have attack value of 50
      }
    }

    class Archer extends Army{
       public Archer(){ 
         attack = 75; // every Archer object will have attack value of 75
       }
    }

有可能吗?还是我需要在每个子类中声明静态变量?我已经尝试过,当我尝试访问静态变量时,每个类的静态变量的值都相同.

Is it possible? Or do I need to declare the static variable in each subclass? I've tried and when I tried to access the static variable, the static variable's value ended up the same for every class.

推荐答案

不,这是不可能的.父类对其子类中的静态或非静态成员一无所知.

No it's not possible. The parent class knows nothing about static or non-static members in it's subclasses.

但是,您发布的代码告诉我您要覆盖静态变量.这也是不可能的,只能覆盖非静态方法(如果它们具有适当的访问级别).

However the code you've posted tells me you want to override a static variable. It's not possible either, only non-static methods can be overriden (if they have the appropriate access level).

这篇关于Java子类中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆