Core Java - [Method Overriding]

♠ Posted by Unknown in at 01:24

Method Overriding (Dynamic Method Dispatch)


In Inheritance When more than one class can have method with same name then the particular method can be called by only on its class object. This is called method overriding.

The Super class object can use to refer the objects of its sub classes. means, the reference of sub classes objects can be given to super class object and then super class object can call any of the method of that class object which it can refer.
If runtime user can change the call of function on his requirement is called "Runtime Polymorphism", "Dynamic Binding", "Late Binding" or "Dynamic Method Dispatch".

//Multilevel Inheritance (Dynamic Method Dispatch)
import java.io.*;
import java.lang.*;

class AExample
{
            private int a;
            public AExample(int x)
            { a = x; }
            void Put()
            { System.out.println("The Main Super Class : " + a); }
};

class BExample extends AExample
{
            private int b;
            public BExample(int x, int y)
            {
                        super(x);
                        b = y;
            }
            void Put()
            { System.out.println("The Intermediate Super Class : " + b); }
};

class CExample extends BExample
{
            private int c;
            public CExample(int x, int y, int z)
            {
                        super(x,y);
                        c = z;
            }
            void Put()
            { System.out.println("The Last Derived Class : " + c); }
};

public class MultiLevelInh
{
            public static void main(String[] args)
            {
                        AExample AObj = new AExample(1);
                        BExample BObj = new BExample(1, 2);
                        CExample CObj = new CExample(5, 6, 7);

                        AObj.Put();

                        AObj = BObj; //Sub Class Object Reference pass to Super Class
                        AObj.Put();

                        AObj = CObj; //Last Sub Class Object Reference pass to Super Class
                        AObj.Put();
            }
}

0 comments:

Post a Comment