I know that private methods are hidden in Derived class and they cant be overridden but my question is different.. Please go through the following problem. My question is mentioned in the problem stated below:
TestPolymorphism.java
class CheckParent {
private void display() {
System.out.println("This is parent class");
}
}
class CheckChild extends CheckParent {
void display() {
System.out.println("This is child class");
}
}
public class TestPolymorphism {
public static void main(String[] args) {
CheckParent cp = new CheckChild();
cp.display(); // This will throw error as display() method id private
// and invisible to child class
}
However, in following code snippet no exception is thrown.
CheckParent.java
public class CheckParent {
private void display() {
System.out.println("This is parent class");
}
public static void main(String[] args) {
CheckParent cp = new CheckChild();
cp.display(); /*This will print "This is parent class" without any error
* my question is why no error is thrown like above case
* as here too display() method is private and invisible to
* derived class */
}
}
class CheckChild extends CheckParent {
void display() {
System.out.println("This is child class");
}
}
}