Advertisement



< Prev
Next >



Method Overriding in Java





In Java, when a class is inherited, you can override the definition of any of its existing accessible methods in its subclass by a feature known as method overriding. Hence in simple words, method overriding is overriding the definition of a superclass method in its subclass.

Besides other rules that we are going to explain for method overriding, one basic rule is that the superclass method being overridden must have the same name in the subclass as well.




Use of method overriding


The key benefit to method overriding is that you can alter the behaviour of the method inherited from a superclass and define its specification according to the need of the subclass.





A simple example of method overriding.



class A				//superclass
{
public void name()		//method name() in class A 
{
System.out.println("A");
}
}

class B extends A		//subclass of A
{
public void name() 		//method name() of class A is overridden in class B
{
System.out.println("B");
}
}

In this example. we have class A inherited by class B. The method name() of class A is returning A but when this method is inherited and overridden by class B, it is returning B.




Rules for method overriding -:








Why method overriding is needed?


Method overriding is mainly used in a situation when we want to create a more specialized version of a generic(general) method inherited from a superclass, within the subclass.



Please share this article -





< Prev
Next >
< Overloading
Constructors in Java >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement

Notifications



Please check our latest addition

PYTHON and DJANGO


Advertisement