Method Overriding in Java

Method Overriding : Method inheritance enables us to define and use methods repeatedly subclasses 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 behaviour when that method is called. That means , we should override the method defined in the superclass. This is possible by defining a method in the subclass that has the same name, same arguments and same return type as a method in the superclass. This is known as overriding.

e.g. /* An example of method overriding*/
class Super
{
int x;
Super(int x)
{
this.x=x;
}
void disp()
{
System.out.println(“Super x=”+x);
}
}
class Sub extends Super
{
int y;
Sub(int x, int y)
{
super(x);
this.y=y;
}
void disp()
{
System.out.println(“Super x=”+x);
System.out.println(“Sub y=”+y);
}
}
class OverrideTest
{
public static void main(String args[])
{
Sub s1=new Sub(100,200);
s1.display();
}
}
Author:- Kritika Saxena