3

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

  • class B is a subclass of class A
  • class B getPrefix() method overrides class' A method
  • class B number attribute overrides class' A attribute
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?

0

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for pointing out the right terminology which helped me find other similar questions on SO, e.g.: stackoverflow.com/questions/13984472/…
@Tanguy I am glad that I could help.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.