0

I have an abstract class that has a static final variable and an instance method defined that references that variable, and I have a non-abstract class that extends that class and overrides the variable:

AClass.java

public abstract class AClass {
    static final int number = 1;

    public void meth(){
        System.out.println(number);
    }
}

IClass.java

public class IClass extends AClass{
    static final int number = 2;
}

I want meth() to print the actual object's class's number, but when I call it with an IClass object, I always get 1, regardless of how it's defined:

AClass o1 = new IClass();
o1.meth(); // 1
IClass o2 = new IClass();
o2.meth(); // 1
new IClass().meth(); // 1

I've added an override that calls the super to IClass, but that didn't help:

IClass.java

public class IClass extends AClass{
    static final int number = 2;

    @Override
    public void meth(){
        super.meth();
    }
}

I've also tried usin this in meth():

AClass.java

public abstract class AClass {
    static final int number = 1;

    public void meth(){
        System.out.println(this.number);
    }
}

Can this be done without completely rewriting the method in IClass.java?

ewok
  • 20,148
  • 51
  • 149
  • 254
  • 1
    The point is that you can't **override** static fields. You resolve the problem by not doing such things. You avoid static where possible; and if you want to adhere to the https://en.wikipedia.org/wiki/Open/closed_principle then you do that using non-static methods! And you know; given your reputation: what kind of prior research did you do? – GhostCat Aug 10 '16 at 21:15
  • You can't override instance fields, either. – Lew Bloch Aug 10 '16 at 23:24

0 Answers0