Declaring a method in
subclass which is already present in
parent class is known as method overriding.
Example:
One of the simplest example – Here
Boy
class extends
Human
class. Both the classes have a common method
void eat()
. Boy class is giving its own implementation to the
eat()
method or in other words it is overriding the method
eat()
.
class Human
{
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human
{
public void eat()//Same name
{
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
obj.eat();
}
}
OUTPUT:
Boy is eating
The main advantage of method overriding is that the class can give its
own specific implementation to a inherited method without even modifying
the parent class(base class).
No comments:
Post a Comment
Note: only a member of this blog may post a comment.