Saturday, 29 December 2018

Overriding method in java - Online Help

Overriding Method in Java:

             An overriding method in java is nothing but a method is overridden when a subclass contains a method with the same name, return type, and parameters(arguments).In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. 


When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class.

   Note: The methods which are declared static in the superclass cannot be overridden by the superclass.

Example:
class supmethod1
{
void display(String str)
{
System.out.println(str);
}
class supmethod2 extends supmethod1
{
void display(String str)
{
super.display(str);
System.out.println(str);
}
}
class overridedemo
{
public static void main(String args[])
{
supmethod1 sm1=new supmethod1();
sm1.display("java");
supmethod2 sm2=new supmethod2();
sm2.display("java beans");
}
}
The output of overloading method in java is:
java
java beans
java beans

In the above program,sm1 is referred to as an object of the class supmethod1 or submethod.supmethod2 is the subclass of supmethod1.

Rules for Overriding Method in Java:

  • Final methods cannot be overridden.because if we don't want a method to be overridden then we declared this as final.
  • The methods which are declared static in the superclass cannot be overridden by the superclass. 
  • Private methods can not be overridden. 
  • We can not override constructor as parent and child class can never have a constructor with the same name(Constructor name must always be same as Class name).

No comments:

Post a Comment