Search code examples
javaclassinheritancemember

Why does changing the type lead to different usage of members?


So I was testing with some code snippets to wrap my head around the concept of inheritance, when I came across this - for me - strange phenomenon.

So first I was testing this simple code:

public class Main{
    public static void main(String[] args) {
        Bar bar = new Bar();

        System.out.println("age = " + bar.age);

        bar.test();
    }
}

class Foo{
    int age = 2;

    void test(){
        System.out.println("TEST FOO");
    }
}

class Bar extends Foo{
    int age = 4;

    void test(){
        System.out.println("TEST BAR");
    }
}

And the output was as I expected:

age = 4
TEST BAR

Then I made a small change to line 3, where I changed the type Bar to Foo like this:

Foo bar = new Bar();

Now when I run the code, it gives me an output I believe is weird:

age = 2
TEST BAR

How does it happen that the code bar.age is now using the age member of the Foo class (which makes sense), while bar.test(); still uses the method of the Bar class (and not from Foo as that is what the type is)?


Solution

  • The age in Bar shadows the age in Foo.

    Furthermore, fields are not polymorphic (cf. functions).

    So when you write Foo bar = new Bar();, the static type of bar is used when accessing the field age, to return 2. And the dynamic type of bar is used when deciding which override of test() to call, and that's a Bar type.