Thursday 13 October 2011

Method overriding


In class hierarchy when a method in subclass has the same name and signature as the method in its super class. Then the method in subclass is said to override method in super class.

when such a overridden method is called through a subclass object  then each time subclass version of that method is called. The version of overridden method of super class is hidden.
Ex,

class A
{
  int i, j;

  A(int a, int b)
 {
    i = a;
    j = b;
  }

  // display i and j
  void show()
  {
    System.out.println("i and j: " + i + " " + j);
  }
}

class B extends A
{
  int k;

  B(int a, int b, int c)
  {
       super(a, b);
       k = c;
  }

  // display k -- this overrides show() in A
  void show()
  {
      System.out.println("k: " + k);
  }

}
 
class Override
{
  public static void main(String args[])
  {
    B subOb = new B(1, 2, 3);
    subOb.show(); // this calls show() in B
  }
}

Why Overridden method?

Overridden method allows supporting runtime polymorphism. It allows a general class to specify methods that will be common to all of its derivatives while allowing subclass to define the specific implementation of some other method.

Dynamic method dispatch (late binding)

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved when the code is executed rather than at compile time means which version of overridden method will be call will be decided at runtime. It is important because this is the way to implement runtime polymorphism. This technique is also  known as Dynamic binding.
Ex,

class A
{
 
   void callme()
    {
        System.out.println("Inside A's callme method");
    }
 }

class B extends A
{
  // override callme()
   void callme()
  {
    System.out.println("Inside B's callme method");
  }
}

class C extends A
{
  // override callme()
  void callme()
  {
    System.out.println("Inside C's callme method");
  }
}

class Dispatch
 {
  public static void main(String args[]) {

    A a = new A(); // object of type A
    B b = new B(); // object of type B
    C c = new C(); // object of type C

    A r; // obtain a reference of type A   

    r = a; // r refers to an A object
    r.callme(); // calls A's version of callme

    r = b; // r refers to a B object
    r.callme(); // calls B's version of callme

    r = c; // r refers to a C object
    r.callme(); // calls C's version of callme
  }
}


Posted by:Ruchita Pandya

1 comment:

  1. Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things
    java training in chennai |
    java training institutes in chennai

    ReplyDelete