This is a code sample of inheritance while the code functions fine.I am unable to understand the output of this code kindly explain it to me.
class R {
private void S1() {
System.out.println("R:S1");
}
protected void S2() {
System.out.println("R:S2");
}
protected void S1S2() {
S1();
S2();
}
}
class S extends R {
private void S1() {
System.out.println("S:S1");
}
protected void S2() {
System.out.println("S:S2");
}
}
public class Inheritance {
public static void main(String srgs[]) {
new S().S1S2();
}
}
The output is:
R:S1
S:S2
Why is the first call made to,R class’ S1 while second to S class’ S2.
R.S1is private, so it’s not called polymorphically, andS.S1doesn’t override it.R.S2is protected, soS.S2overrides it, and when you callS2on an instance ofS2(even if it’s only statically known to be an instance ofR),S.S2will be called.From section 8.4.8.1 of the JLS:
Note how
m2can’t be private.