In: Computer Science
Write 3 classes with three levels of hierarchy: Base, Derive (child of base), and D1 (child of Derive class). Within each class, create a “no-arg” method with the same signature (for example void m1( ) ). Each of this method (void m1( ) ) displays the origin of the Class type. Write the TestDynamicBinding Class: (the one with the ‘psvm’ ( public static void main (String[] args)) to display the following. You are NOT allowed to use the “standard object.m1() “to display the message in the main(…) method. That would NOT be polymorphic! (minus 10 points for not using polymorphic method) Explain why your solution demonstrates the dynamic binding behavior? (minus 5 points for lack of explanation) From Parent Class From Derived:Parent Class From Derived:Parent Class From D1:Derived Class Explain why this demonstrates dynamic polymorphism: (minus 4 points for lack of explanation)
class Base
{
void m1()
{
System.out.println("Origin: Base Class");
}
}
class Derive extends Base
{
void m1()
{
System.out.println("Origin: Derived Class");
}
}
class D1 extends Derive
{
void m1()
{
System.out.println("Origin: D1 - Child of Derive Class");
}
}
class TestDynamicBinding
{
public static void main(String args[])
{
Base base = new Base(); // object of Base class
Derive derive = new Derive(); // object of Derive class
D1 d1 = new D1(); // object of D1 class
Base reference; // Reference of type Base
reference = base; // reference referring to the object of Base
class
reference.m1(); //call made to Base Class m1
method
reference = derive; // reference referring to the
object of Derive class
reference.m1(); //call made to Derive Class m1 method
reference = d1; // reference referring to the object
of D1 class
reference.m1(); //call made to D1 Class m1 method
}
}
Explanation:
1) Here we have used Method overriding to supports dynamic binding. A linking procedure call to the overridden method m1() is made at run time rather than doing it at the compile time. The code to be executed for this specific procedural call is also known at run time only.
Base base = new Base(); Base reference;
reference = base; reference.m1() -> makes a call to m1() method
of Base class at run time
Similarly,
reference = derive; reference.m1() -> makes a call to m1() method of Derive class at run time
reference = d1; reference.m1() -> makes a call to m1() method of D1 class at run time
2) Base reference; This is the superclass reference and Java determines which method will be executed based upon the type of the object being referred to it at the run time of the call.
eg:
reference = derive; reference.m1().
Here, 'derive' is the object of the Derive class and 'reference' is referred to the it.
So, the method m1() of Derive class is executed at run-time.