I want to have the same static variable with a different value depending on the type of class.
So I would have
public class Entity
{
public stat
A quick test will show you that, yes, you can override static variables in subclasses.
I have put together a simple inheritance structure to test this. StaticTest is the super of StaticTestSub. They both declare static ints TEST1
, TEST2
, and TEST3
with varying degrees of access. To simplify the example, I left out the private
version.
public class StaticTest {
public static int TEST1 = 1;
protected static int TEST2 = 1;
static int TEST3 = 1;
public static void main(String[] args) {
System.out.println("StaticTest.TEST1: " + StaticTest.TEST1);
System.out.println("StaticTest.TEST2: " + StaticTest.TEST2);
System.out.println("StaticTest.TEST3: " + StaticTest.TEST3);
System.out.println("StaticTestSub.TEST1: " + StaticTestSub.TEST1);
System.out.println("StaticTestSub.TEST2: " + StaticTestSub.TEST2);
System.out.println("StaticTestSub.TEST3: " + StaticTestSub.TEST3);
}
}
public class StaticTestSub extends StaticTest {
public static int TEST1 = 2;
protected static int TEST2 = 2;
static int TEST3 = 2;
}
You can try this at home. The out put was:
StaticTest.TEST1: 1
StaticTest.TEST2: 1
StaticTest.TEST3: 1
StaticTestSub.TEST1: 2
StaticTestSub.TEST2: 2
StaticTestSub.TEST3: 2
For your specific needs, however, I recommend the approach taken by Laurence Gonsalves