Remove Override Solution – 4: Dynamic Method Dispatch

Dynamic method dispatch is 4th solution of remove override methods from java programs. In this blog we will see how to stop override method using dynamic method dispatch.

 

Example on Dynamic Method Dispatch

class A

{

                void method()

                {

                                System.out.println(“Welcome in A”);

                }

}             

class B extends A

{

                void method()

                {

                                System.out.println(“Welcome in B”);

                }

}             

class C extends B

{

                void method()

                {

                                System.out.println(“Welcome in C”);

                }

}

class inh10

{

                public static void main(String args[])

                {

                                //C c1 = new C();

                                //c1.method(); // Override all method and display C Class o/P   

 

                                // How to dispatch all methods

                                A a1 = new A();

                                B b1 = new B();

                                C c1 = new C();

 

                                A ref;     // Ref

                                ref = a1;               // assign a1 object into ref

                                ref.method();    // call to direct A class method()

 

                                ref = b1;               // assign b1 object into ref

                                ref.method();    // call to direct B class method()

 

                                ref = c1;                // assign c1 object into ref

                                ref.method();    // call to direct C class method()

                }

}

Output:

Welcome in A

Welcome in B

Welcome in C

 

About Programs.

In this program, we create Super Class A’s references and then assign object of B and C sub class. Using of this A class reference we can call all override method.

Video available on YouTube.


Earn Money Online

658total visits,8visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Your comments (*)

Name (*)

Your full name please.

Email address (*)

Used for gravatar.

Website

Link back if you want.

Enter Captcha Here :*

Reload Image