“Poly” means many and “morphos” means forms………blah,blah,blah,blah…………….

Let’s do some coding,

class Stucture

{

         public void design()

        {

                System.out.println(“DVD design”);

          }

class House extends Structure

{

         public void design()

        {

                System.out.println(“house Design”);

          }

          public static void main(String[] args)

           {

                          Structure s=new House();//since house is a structure a valid assignment

                           s.design();          //polymorphism comes into play and a house is designed, nothing very impressive

            }

In the code above a house object is created at runtime and the JVM facillitates the calling of exact overridden design method depending on the type of object as the JVM knows the type of the object being created at runtime. 

Till now , its smooth, we used a superclass reference pointing to its subclass object to demonstrate polymorphism, but what about the case when we pass polymorhic argument method, where 2 overloaded versions of that method exist, one takes a superclass object and other one relies on a subclass object,

class DVD

{

 public void design(DVD dd)

{

System.out.println(“general Dvd”);

}

}

class TestDVD extends DVD

{

public void design(DVD dd)

{

System.out.println(“DVD Design”);

}

public void design(TestDVD dd)

{

System.out.println(“TestDVD Design”);

}

public static void main(String[] args)

{

TestDVD td=new TestDVD();

DVD s=new TestDVD();

td.design(s);

}

}

 

 

No, No, No………captain kirk the output will not be “TestDVD design”, it will be “DVD design”, but why so??……the JVM stilll knows the object being passed is actually a TestDVD so appropriate method should be called, but this is the point where it gets funny, REMEMBER, the choice of which overloaded method to call for which type of argument is not decided at runtime, it is a compile time based choice, the method signature “freezes” at compile time.

Advertisements