0

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?

Coronero
  • 160
  • 1
  • 9
oddity
  • 77
  • 7
  • 7
    Don't see any difference between the two code blocks. – Robby Cornelissen Jul 04 '19 at 10:10
  • When you override a method include @Override annotation and your compiler will tell you if you've successfully overriden a method or not. – matt Jul 04 '19 at 10:28
  • @RobbyCornelissen their edit needs an approval. Maybe you or somebody upvoting your comment could approve the edit. – matt Jul 04 '19 at 10:43

1 Answers1

0

The problem is that your object is of type TreeGrow. Your main method therefore calls the method TreeGrow.grow(). The private method is not overridden and therefore the "most-suitable" method is called, which is the private void grow() one.

You need to cast your object to the corresponding type to use its method. Try using ((Oak)tree).grow (or alternatively Oak tree = new Oak();). This should execute your method.

Edit: Sorry for the "vague" explanation. I was in a hurry and wanted to help as fast as possible. After re-visiting this, it really is not well-written. As the linked "duplicate" question (and the respective answers) describe everything in a more elaborate manner, I would recommend reading there.

Coronero
  • 160
  • 1
  • 9
  • 2
    This is a strange situation. I downvoted you at first and now I cannot remove it. Can you improve your explanation a little bit? Your answer seems to imply that casting is changing the object, but the two main points are. TreeGrow.grow is a different method than Oak.grow, and casting causes the compiler to choose the Oak method. Essentially they've shadowed TreeGrow.grow but not overriden. – matt Jul 04 '19 at 10:36