I am puzzled by this inheritance example found in a quizz from a Coursera Java course:
getPrefix() method overrides class' A methodnumber 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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With