1

For example:

class RuntimePolymorphismDemo {

  public static void main(String[] args) {
    Animal ref1 = new Animal();
    Animal ref2 = new Dog();
    Animal ref3 = new Cow();
    Animal ref4 = new Snake();
    ref1.whoAmI();
    ref2.whoAmI();
    ref3.whoAmI();
    ref4.whoAmI();
  }
}

What it is the purpose of defining ref1, ref2, ref3 and ref4 variables of type Animal if you can define them like this:

    Animal ref1 = new Animal();
    Dog ref2 = new Dog();
    Cow ref3 = new Cow();
    Snake ref4 = new Snake();

And you can call the method whoAmI() directly? What do you gain using the parent class?

Thanks.

Juan Perez
  • 13
  • 2

2 Answers2

1

Looks to be valid and reasonable ask in context of example you quoted. Going back to basic definition of run time ploymorphism is "same interface but different implementation"

So in your example : Animal basically provides you an interface whoAmI(). But you will get behavior of actual type that variable Animal points to (this is called run time dispatch or dynamic dispatch) depending upon concrete implementation of that type:

ref2.whoAmI(); /* will say I am Dog */
ref3.whoAmI(); /* will say I am snake*/

What is the point of this behavior : Its one of the most important concept of OOP which facilitate encapsulation for example.

For example : You might have one method which does a lot of thing. It will display animal name, animal picture and history. Lets say that method looks something like :

public void ShowAnimalInfo(Animal animal)
{

   animal.WhoAmI();
   var picture = animal.GetImage();
   var history = animal.GetHistory();
   /* statement and logic to process picture and history on some UI */
}

Now the consumer of this method can use this method like :

ShowAnimalInfo(new Dog()); /*OR*/
ShowAnimalInfo(new Cow());

If you notice, your method ShowAnimalInfo() is abstracted from actual animal and can be re used by just working on interface provided by Animal and let run time take care of invoking actual implementation.

rahulaga-msft
  • 3,964
  • 6
  • 26
  • 44
0

The whole purpose of OOP is that on object's implementation must be hidden, so in a strict OOP style, when we use an object we care about its protocol (interface) and when we construct an object we care about its implementation, giving it its special characteristics. So the correct OOP style is the first:

Animal ref2 = new Dog();

After its instantiation there is no 'Dog' concept, but just an 'Animal'. This misunderstanding arises because in most modern OOP languages a Class can be also a Type, but these are actually different concepts. See also this SO question: Object-oriented languages without class concept.