Originally posted by Kathy Hodgson:
The reference is to an instance of S2. S2 inherits display(), so why isn't that call printing S2's own String s instead of its parent's?
public class Question{
String s = "Outer";
public static void main(String[] args){
S2 s2 = new S2();
s2.display();
}
}
class S1 {
String s = "S1";
void display() {
System.out.println(s);}
}
class S2 extends S1{
String s = "S2";
}
Could somebody please explain it?
If a child class inherits a method without changing it, doesn't it really have it at all?
The only way any of this makes sense to me is if the child class doesn't really have any method it inherits without overriding - in other words, it is not calling its own invisible copy of the display method (which is how I thought method inheritance worked) but is calling its parent's display method.
SCJP 1.4, SCWCD, SCBCD, IBM XML, IBM Websphere 285, IBM Websphere 287
Also working all 19 of Dan Chisholms exams helped.
Static method Q.printS1 hides the static method P.printS1 in the super class P. Instance method Q.printS2 overrides the instance method P.printS2. Due the the differences between the hiding of static methods and the overridding of instance methods the invocation of the two methods in P.printS1S2 produces different results. The method invocation expression printS1 results in the invocation of the hidden super class method P.printS1. The method invocation expression printS2 results in the invocation of the overridding sub class method Q.printS2.
SCJP 1.4, SCWCD, SCBCD, IBM XML, IBM Websphere 285, IBM Websphere 287
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |