CODE:1
class Ajay {
private void display() {
System.out.println("Ajay");
}
public static void main(String ...strings ){
Ajay r=new Ravi();
r.display();
}
}
class Ravi extends Ajay{
public void display() {
System.out.println("ravi");
}
}
CODE:2
class Ravi {
private void display() {
System.out.println("ravi");
}
}
public class Ajay extends Ravi{
public void display() {
System.out.println("ajay");
}
public static void main(String ...strings ){
Ravi r=new Ajay();
r.display();
}
}
I have a doubt in the above two codes.
CODE 1 executes without any error while CODE 2 throws an error like The method is not visible.
What is the reason for this error??
In your second example you try to call a method
display()on a variable of typeRavi.Ravihas no methoddisplay()that’s accessible from this location (i.e. insideAjay).In your first example, however you call the private
display()method ofAjayfrom withinAjay. Note that callingprivatemethods does not use runtime polymorphism! The exact code to be called is decided at compile-time!