Tanguy
Tanguy

Reputation: 3304

Java - attribute inheritance example

I am puzzled by this inheritance example found in a quizz from a Coursera Java course:

class ClassA {
    protected int number;

    public ClassA() {
        number = 20;
    }

    public void print() {
        System.out.println(getPrefix() + ": " + number);
    }

    protected String getPrefix() {
        return "A";
    }
}

class ClassB extends ClassA {
    protected int number = 10;

    protected String getPrefix() {
        return "B";
    }
}



public class Quizz {

    public static void main(String[] args) {

        ClassB b = new ClassB();
        b.print();

        ClassA ab = new ClassB();
        ab.print();

    }
}

When we run this program, the printed result is:

B: 20
B: 20

However, I was expecting this result instead:

B: 10
B: 10

Can you explain how come class A number attribute is printed, and not class B?

Upvotes: 3

Views: 333

Answers (2)

Jason
Jason

Reputation: 5246

Yeah so you can override a method from a super class but you cannot declare another class member with the same name. You're creating a new class member with the name number. It would only refer to 10, the value from the super class #number if you used super.number instead of this.number.

Upvotes: 3

Eng.Fouad
Eng.Fouad

Reputation: 117587

Can you explain how come class A number attribute is printed, and not class B?

ClassB does not inherit ClassA.number field, but rather hides it.


See:

Within a class, a field that has the same name as a field in the superclass hides the superclass's field.

Upvotes: 7

Related Questions