Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variable in subclass Java

Tags:

java

object

oop

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.

let's say:

    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.

like image 549
Rei Avatar asked Dec 08 '14 09:12

Rei


People also ask

Do classes inherit static variables?

Thanks for the answer. 1 line compiles it all "Static variables are inherited as long as their are not hidden by another static variable with the same identifier."

Can a static variable be called in another class inheriting the previous class?

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor. However, they can contain a static constructor.

Does a subclass inherit variables?

A subclass also inherits variables and methods from its superclass's superclass, and so on up the inheritance tree.

Are static variables stored in heap Java?

Storage Area of Static Variable in JavaAfter the java 8 version, static variables are stored in the heap memory.


2 Answers

Your current code won't do what you want, since there is only one attack variable in Army class, and it can have only one value.

You could have a method in Army that returns a default value :

public int getAttack()
{
    return 10;
}

Then you can override this method in your sub classes :

class Warrior extends Army
{
    ...
    @Override
    public int getAttack()
    {
        return 50;
    }
    ...
}

class Archer extends Army
{
    ...
    @Override
    public int getAttack()
    {
        return 75;
    }
    ...
}

Even though getAttack() is not a variable, and it's not static, it still fulfills your requirements - each sub-class can have a different value shared by all instances of that sub-class.

like image 145
Eran Avatar answered Oct 18 '22 20:10

Eran


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).

like image 5
iozee Avatar answered Oct 18 '22 20:10

iozee