Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public attributes and inheritance Java

Tags:

java

I'm checking some Java exercises but I'm confused with this one:

We have a Foo class with this structure:

public class Foo {
    public int a = 3;

    public void addFive() {
        a += 5;
    }
}

A Bar class who inherits from Foo:

public class Bar extends Foo {
    public int a = 8;

    public void addFive() {
        a += 5;
    }
}

And a Test class :

public class Test {

    public static void main(String[] args) {
        Foo f = new Bar();
        f.addFive();
        System.out.println(f.a);
    }
}

I would think the output is 13, but it's 3, my question is Why?..

like image 582
Rafael Carrillo Avatar asked Feb 20 '26 09:02

Rafael Carrillo


1 Answers

Adding to Peter's answer : keep in mind that member variables are not polymorphic, so they are not overriden.
I.e. f.a still gives you reference to super class's a (since f's declared type is Foo) whereas f.addFive() calls method on Bar, (since f's runtime type is Bar);

So, for example

Bar b = new Bar();
Foo f = b;
f.addFive();
System.out.println(f.a); // prints 3
System.out.println(b.a); // prints 13 as you have expected

Hope it is clear.

like image 167
kiruwka Avatar answered Feb 22 '26 23:02

kiruwka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!