I am trying to run a java program to implement the overridding the grow
method.
The overridding works perfectly if method grow
in class Tree
(parent class) is declared with default access modifier and prints "Oak is growing"
.
But when its changed to private
, the method from the parent class (Tree
) executes.
// Code with grow() default modifier
public abstract class TreeGrow {
void grow() {
System.out.println("Tree is growing");
}
public static void main(String args[]) {
TreeGrow tree = new Oak();
tree.grow();
}
}
class Oak extends TreeGrow {
protected void grow() {
System.out.println("Oak is Growing");
}
}
// Code with private grow
public abstract class TreeGrow {
private void grow() {
System.out.println("Tree is growing");
}
public static void main(String args[]) {
TreeGrow tree = new Oak();
tree.grow();
}
}
class Oak extends TreeGrow {
protected void grow() {
System.out.println("Oak is Growing");
}
}
Why is the private method in Tree
class executed, when the method is called through Oak object?