In
situations where a method in a subclass has the same name and type signature as
a method in its superclass, then the method in the subclass is said to override the method in the superclass.
    When
an overridden method is called from within a subclass, it will always refer to
the subclass version of the method. The version of the method defined by the
superclass will be hidden.
     Ex:class
Base
{
 void show()
 {
 
System.out.println("Base class show method is called");
 }
}
class
Derive extends Base
{
 void show() //show method is overridden
 {
 
System.out.println("Derive class show method is called");
 }
}
class
Override
{
public
static void main(String args[])
 {
 
Derive s=new Derive();
 
s.show();
 }
}
Output:Derive
class show method is called
    Dynamic Method
Dispatch:
o   Dynamic
Method Dispatch is a mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
o   Dynamic
Method Dispatch is important because this is how java implements run time polymorphism.
o   When
an overridden method is called through a superclass reference, Java
determineswhich version of that method to execute based upon the type of the
object being referred to at the time of call occurs.
    Ex: class
Base
{
 void show()
 {
 
System.out.println("Base class show method is called");
 }
}
class
Derive1extends Base
{
 void show() //show method is overridden
 {
 
System.out.println("Derive class 1 show method is called");
 }
}
class
Override
{
public
static void main(String args[])
 {
 
Base b=new Base();
 
Derive1 d1=new Derive1();
Base r;
 
r=b;
 
r.show();
r=d1;
 
r.show();
 }
}
Output:Base
class show method is called
          Derive
class 1 show method is called
 
 
 

No comments:
Write comments