203k views
1 vote
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

User Med Besbes
by
5.7k points

1 Answer

3 votes

Answer:

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

}

}

Step-by-step explanation:

The solution demonstrates dynamic binding behavior because the linking procedure used calls overwritten 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.

User Zinking
by
6.4k points