Search code examples
javasubclasssuperclass

superclass attribute overrides subclass attribute


I have a class with many subclasses,but when passing a subclass instance to some method which is supposed to receive an instance of the superclass, the attribute of the subclass is overwritten.

For example, the following code prints 0. What should I do to it so that it prints the subclass parameter value?

class A{
    int cost;
}

class B extends A{
    int cost = 10;
}

class Test{
    public static void main(String[] args){
        B b = new B();
        method4A(b);

    }

    static void method4A(A a){
        System.out.println(a.cost);
    }
}

Solution

  • While fields can be shared within inheritance, given the right access modifiers (i.e. anything not private pretty much - default access will not work across different packages though), they are resolved at compile time, contrary to methods which are resolved at runtime (the latter is called virtual method invocation).

    ints default to 0, and you're passing an A reference type, so A.cost's value of 0 is printed.

    You have a range of options here:

    • Do not declare cost in B and assign cost value from A in B's constructor, or instance initializer, etc. to 10
    • An ugly, explicit cast in method4A, e.g. System.out.println(((B)a).cost);
    • Passing a B reference type instead of A in method4A
    • Keep both cost variables and declare a simple getter in A returning cost, and @Override it in B with the same implementation (it'll return B's cost even when invoked on a A reference if the instance actually is B)