Explain About Method Overriding in Java with Example ?

A Method defined in a super class is inherited by its subclass and is used by the objects created by the subclass. Method i...


A Method defined in a super class is inherited by its subclass and is used by the objects created by the subclass. Method inheritance enables us to define and use methods repeatedly in subclass without having to define the methods again in subclass.

However, there may be occasions when we want an object to respond to the same method but have different behavior when that method is called that means, we should override the method defined in the super class.

This is possible by defining a method in the sub class that has the same name, same arguments and same return type as a method in the super class. Then when that method is called, the method defined in the sub class is invoked and executed instead of the one in the super class. This is known as overriding.

Method overriding means same name & same signature.

Ex :

class super
{
int x;
super (int a)
{
x = a;
}

void display ( )
{
System out println (“super x = “ + x) ;
}
}

class sub extends super
{
int y ;
sub (int a, int b)
{
super (a) ;
y = b ;
}

void display ( )
{
System out println (“super x = “ + x) ;
System out println (“Sub y = “ + y) ;
}
}

class override
{
public static void main (String a [ ])
{
sub s1 = new sub (10, 20) ;
s1. display ( ) ;
}

O/P :– super x = 10 ;
            sub y = 20


Post a Comment

emo-but-icon

item