Write About Method overriding in Java?

Method overriding:

A method defined in a super class is inherited by its subclass and is used by the objects created by the subclass .method inheritance enable us to define and use methods repeatedly in sub classes 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 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 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.

Ex:

class Super
{
int x;
Super(int x)
{
this.x=x;
}
void display( )
{
System.out.println(“super x=”+x);
}
}

class Sub extends Super
{
int y;
Sub(int x, int y)
{
super(x);
this.y=y;
}
void display( )
{
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( );
}
}

Related

Java 1109301504162668618

Post a Comment

emo-but-icon

item