16

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

moffeltje
  • 4,521
  • 4
  • 33
  • 57
  • 2
    https://stackoverflow.com/questions/12589274/slight-confusion-regarding-overriding-where-variables-are-concerned or https://stackoverflow.com/questions/10722110/overriding-member-variables-in-java –  Dec 05 '17 at 11:50
  • @RC. Interesting reads, was looking for that. Thanks. – moffeltje Dec 05 '17 at 12:08
  • 1
    Beside the technical aspect: doing so this is **not** OOP since it violates the most important OO principle: *information hiding / encapsulation*. – Timothy Truckle Dec 05 '17 at 12:09

2 Answers2

22

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
4

Because you have defined two different age fields, one in each class. Fields are not overridden.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24