'Why Java super method uses getter of child when extending and overriding [duplicate]
public class MyClass {
public static void main(String args[]) {
class MyClassA {
private String name = "testA";
public String getName() {
return name;
}
public void printName() {
System.out.println(this.getName());
}
}
class MyClassB extends MyClassA {
private String name2 = "testB";
public String getName() {
return name2;
}
public void printName() {
super.printName();
System.out.println(getName());
}
}
MyClassA classA = new MyClassA();
MyClassB classB = new MyClassB();
System.out.println("Print name in A:");
classA.printName();
System.out.println("Print names in B:");
classB.printName();
}
}
Output is:
Print name in A:
testA
Print names in B:
testB
testB
My question is why it printed "testB" both times in the end. I would have expected it would be "testA testB" because the first "printName" in MyClassB called the super method.
Is it possible to make it work so that it prints "testA testB"?
Solution 1:[1]
To make the output print "testA testB", you have to avoid overriding the getName() method.
A simple fix would be to change the name of one method, if the getName() method of MyClassB was changed to getName2() as follows,
class MyClassB extends MyClassA {
private String name2 = "testB";
// change name here
public String getName2() {
return name2;
}
public void printName() {
super.printName();
System.out.println(getName2());
}
}
you will get the desired output. Checkout these rules for method overriding for further reference.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anye |
