Method Overriding in Java

Method Overriding means having two methods with the same method name and same signature. One of the methods is in the parent class and the other is in the child class.

Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class.

 

Rules for Method Overriding

  • The first rule is, you can only override a method in the subclass. You can not override the method in the same class.
  • The second rule is, Method name and signature of the method must be same in Superclass and Subclass or in an interface and its implementation.
  • The third rule to override the method in Java is that overriding method can not reduce accessibility of overridden method in Java. For example, if overridden method is public than overriding method can not be protected, private, But the opposite is true overriding method can increase accessibility of method in Java, i.e. if overridden method is protected than overriding method can be protected or public.
  • Another rule of method overriding in Java is that overriding method can not throw checked Exception which is higher in the hierarchy than overridden method. Which means if overridden method throws IOException than overriding method can not throw java.lang.Exception in its throws clause because of java.lang.The exception comes higher than IOException in Exception hierarchy. This rule doesn’t apply to RuntimeException in Java, which is not even needed to be declared in throws clause in Java.
  • You can not override the private, static and final method in Java. private and static method are bonded during compile time using static binding in Java and doesn’t resolve during runtime. an overriding final method in Java is compiled time error.
  • Overridden method is called using dynamic binding in Java at runtime based on the type of Object.

 

Selenium Testing Video Tutorial:

 

An example of Method Overriding:

In the below example we are overriding the display() method of parent class into its child class.

Output:

display() method of Child class
stub() method of Child class
Dummy() method of super class

0 Comment

Leave a Reply