-2

What will happen for the following statements in Java:

SuperclassObject o = new SubclassObject();

then we run

o.randomMethod();

However, randomMethod() has been implemented in both SuperclassObject and SubclassObject, but in different ways. Which method will be called??

  • 3
    Possible duplicate of [Polymorphism vs Overriding vs Overloading](https://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading) – Logan Jul 19 '18 at 03:23
  • 3
    Have you considered testing? – shmosel Jul 19 '18 at 03:23
  • https://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading Try this. – Shadab Siddiqui Jul 19 '18 at 03:24
  • What do you mean `in different ways`? Do you mean a different argument list, changed to a static function or something else? Changing it would almost certainly entail calling the function differently, so there couldn't be any ambiguity. – Paul Rooney Jul 19 '18 at 03:48

1 Answers1

1

It will call the subclass version. Why? Because there is only one concrete object in memory and that object belongs to the subclass.

Yes, the subclass can act as the superclass but in the inside it has only its own implementation of the method.

Camilo Sanchez
  • 117
  • 1
  • 7