0

Can someone explain to me why the output of the following code is "From app class". I cannot wrap my head around it.

public abstract class App
{
    private void run()
    {
        System.out.println("From app class");
    }

    public static void main(String[] args) {
        App object = new OtherClass();
        object.run();
    }
}

class OtherClass extends App
{
    protected void run()
    {
        System.out.println("From otherclass");
    }
}

Result: From app class

And why is it when I change to this line of code, the output is "From otherclass":

public static void main(String[] args) {
      OtherClass object = new OtherClass();
      object.run();
}
Douma
  • 2,682
  • 14
  • 23
  • 6
    Because private methods aren't polymorphic: the subclass can't override a private method from the superclass since its method is private, and is thus known only from the superclass. So, when you have a variable whose declared type is App, and you call run() on this variable, the only possible method that matches is the private App.run() method, which isn't called polymorphically since it's private. Make the method protected, and it will invoke the one from the subclass, which will then override it. – JB Nizet Oct 16 '19 at 22:03
  • Use comments to ask for more information or suggest improvements. Avoid answering questions in comments. (Make that an answer, for creating an answer to the question you should get the reputation @JBNizet) – FailingCoder Oct 16 '19 at 22:08
  • 5
    Thanks @FailingCoder. I know how this site works. I have 500k+ rep points already :-) I did post as a comment mainly beacause I'm sure there are dozens of duplicates already, but I'm too lazy to search for them. – JB Nizet Oct 16 '19 at 22:11

0 Answers0