Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Method Overriding in Java with Examples

I have already shared what is method overloading and its examples in detail. Method Overloading and Method Overriding are the topics which should be in your to do list before appearing for the interview. In this post I will share what is method overriding, rules of method overriding and examples. So let's dive in and understand method overriding in java.

First you should be familiar with the term "parameter". If you don't know what are parameters, then please check here. Now you are ready to understand what is method overriding.

Read Also :  Difference between Method Overloading and Method Overriding

What is Method Overriding

When the child class(subclass) has the method which has the same name, same parameters and same return type (or covariant return type) as a method in its parent class(or super-class), then child method has overridden the parent class method.


Runtime polymorphism can be achieved through method overriding.Remember that at runtime, Object type (not reference variable's type) determines which overridden method is used.
If parent class object is used to invoke the method, then the parent class method will be executed. Otherwise, if , child class object is used to invoke the method, then the child class method will be executed.

Example of Method Overriding



// Method Overriding Example

//Base class
class Parent {
public void display() {
System.out.println("parent method is executed");
}
}

//Derived or Inherited class
class Child extends Parent {

//Below method overrides the Parent display() method
@Override
public void display() {
System.out.println("child method is executed");
}
} 
 
//Driver class
public class Main {
public static void main(String args[])
{
// If a Parent type reference refers
// to a Parent object, then Parent's
// display() is called
Parent parentObject = new Parent();
parentObject.display();

// If a Parent type reference refers
// to a Child object Child's display()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent childObject = new Child();
childObject.display();
}
}


Output :
parent method is executed
child method is executed


Rules for Method Overriding in Java

1. Access Modifiers and Overriding

The access level can't be more restrictive than the overridden method's. The access level can be less restrictive than that of overridden method. 

For example, a protected instance method in the parent class(super class) can be made public but not private in the child class(subclass). If you try to make child class private then it will give compile time error.


// Access Modifiers and Overriding Example

//Base class
class Parent {
//Access modifier of parent's display() method is protected
protected void display() {
System.out.println("parent method is executed");
}
}

//Derived class
class Child extends Parent {

//Below method overrides the Parent display() method
//Access modifier public is less restrictive than protected 
@Override
public void display() {
System.out.println("child method is executed");
}
}
//Driver class
public class Main {
public static void main(String args[])
{
Parent parentObject = new Parent();
parentObject.display();

Parent childObject = new Child();
childObject.display();
}
}

Output :
parent method is executed
child method is executed

2. Private Methods can not be Overridden

Another rule regarding access modifiers is you can not override private methods in parent class.If subclass tries to override the private method of parent class then program will throw compile time error as shown below.

// Access Modifiers and Overriding Example

//Base class or Superclass
class Parent {
//Access modifier of parent method is private
// This method can not override the child class method
private void display() {
System.out.println("parent method is executed");
}
}

//Derived class or Subclass
class Child extends Parent {

//Below method can not overrides the Parent display() method
//This method is unique to the child class
private void display() {
System.out.println("child method is executed");
}
}
//Driver class
public class Main {
public static void main(String args[])
{
Parent parentObject = new Parent();
parentObject.display(); // this line when execute will throw compiler error

Parent childObject = new Child();
childObject.display(); // this line when execute will throw compiler error
}
}


3. Final Methods can not be Overridden in Java

You can not override a method marked final. It will throw compile time error if you try to do so.

// Simple Java program showing 
// final methods cannot be overridden
//Parent class or Superclass
class Parent
{
// Can't be overridden
final void display() { }
}
//Child class or Subclass
class Child extends Parent
{
// This would produce compile time error
void display() { }
}

Output :
/Main.java:13: error: display() in Child cannot override display() in Parent
    void display() {  }
         ^
  overridden method is final
1 error

4. Static Methods can not be Overridden

You can not override a method mark static. If you define a static method  in the subclass (child class) with the same method signature as the super class(parent class) then it is called method hiding.

// Method hiding example

//Base class or SuperClass
class Parent {

static void display() {
System.out.println("parent static method is executed");
}

void show() {
System.out.println("parent non-static (instance) method is executed");
}
}

//Derived class or SubClass
class Child extends Parent {

//This method hides the Parent display() method
static void display() {
System.out.println("child static method is executed");
}
// This method overrides the Parent show() method
void show() {
System.out.println("child non-static (instance) method is executed");
}
}

//Driver Class
public class Main {
public static void main(String args[])
{
Parent childObject = new Child();
// static method can not be overridden,
// so below line calls parent display() method
childObject.display();
// Expected child method will run
childObject.show();
}
}

Output:
parent static method is executed
child non-static (instance) method is executed


5. Invoking a SuperClass (Parent class) version of Overridden Method

It's easy to call the SuperClass(Parent class) version of Overridden Method by using the super keyword.

// Invoking SuperClass version of Overridden Method Example

//Base class or SuperClass
class Parent {

void display() {
System.out.println("parent method is executed");
}
}

//Derived class or SubClass
class Child extends Parent {

//This method overrides the Parent display() method
@Override
void display() {
super.display();
System.out.println("child method is executed");
}
}

public class Main {
public static void main(String args[])
{
Parent childObject = new Child();
childObject.display();
}
}

Output :
parent method is executed
child method is executed


6. Overriding Method must have the Same return type (or Covariant return type)

The method return type must be same, or a subtype of, the return type declared in the original overridden method in the superclass. 
Since java 5.0 it is made possible to have a different return type for a overriding method in a child class. But child's return type should be a sub-type of parent's return type. This phenomenon is called covariant return type.

Example of Covariant Return Type

class Alpha {
Alpha doStuff(char c) {
return new Alpha();
}
}
class Beta extends Alpha {
Beta doStuff(char c) { // legal override in Java 1.5
return new Beta();
}
}
public class Main {
public static void main(String args[])
{
Alpha childObject = new Beta();
childObject.doStuff('a');
}
}

The above code will compile and run.


7. Constructor and Overriding

You can not override constructor as the constructor name of the base class and child class can never be same. (Constructor name is always same as the Class name).


8. Exception Handling and Overriding

Rule 1. The overriding method can throw any unchecked(runtime) exception regardless of whether the overridden method declares the exception.

// Overriding when superclass does not throw an exception

//Base class or SuperClass
class Parent {
//overridden method
void display() {
System.out.println("parent method is executed");
}
}

//Derived class or SubClass
class Child extends Parent {

//This method overrides the Parent display() method
//It throws unchecked exception i.e Arithmetic Exception
@Override
void display() throws ArithmeticException{
System.out.println("child method is executed");
}
}

public class Main {
public static void main(String args[])
{
Parent childObject = new Child();
childObject.display();
}
}

Output:
child method is executed

Rule 2. The overriding method must not throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException can not be overridden by a method that declares a SQLException, Exception or any other non-runtime exception unless it's a subclass of FileNotFoundException.

Note :  The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass' exception takes the same risks.
Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares.


9. Abstract method and Overriding

Abstract methods can only be overridden by the first concrete class (classes that have no abstract methods) otherwise a compiler error will be thrown.

//Abstract class  
abstract class Parent
{
public abstract void display( int x, String j);
}
//Subclass or Derived Class
class Child extends Parent
{
@Override
public void display( int x, String j )
{
System.out.println("child method is executed");
}
}
//Driver class
public class Main {
public static void main(String args[])
{
Parent childObject = new Child();
childObject.display(1, "Alive is Awesome");
}
}

Output :
child method is executed


10. Synchronized/strictfp method and Overriding

Synchronized or strictfp methods does not have any impact on overriding method. So it's possible that a non synchronized or non strictfp method can override a synchronized/strictfp method or vice versa.

MultiLevel Method Overriding in Java

In multilevel method overriding we create a grandchild class and override the display() method of the parent class. Lets find out what will happen if we perform runtime polymorphism in multilevel overriding.

// MultiLevel Overriding

//Base class or SuperClass
class Parent {
//overridden method
void display() {
System.out.println("parent method is executed");
}
}

//Derived class or SubClass
class Child extends Parent {

//This method overrides the Parent display() method
@Override
void display() {
System.out.println("child method is executed");
}
}
//Inherited Class
class GrandChild extends Child {

// This method overrides the Parent display() method
@Override
void display() {
System.out.println("grand child method is executed");
}

}
//Driver Class
public class Main {
public static void main(String args[])
{
Parent grandchildObject = new GrandChild();
grandchildObject.display();
}
}

Output:
grand child method is executed


Examples of Legal/Illegal Method Overrides

Let's have a simple class Animal with the eat() method.

public class Animal {
public void eat() { }
}

Below are the list of the legal/illegal overrides of Animal eat() method

1. private void eat() {} - Illegal override code. Access modifier is more restrictive.

2. public void eat() throws IOException {}  - Illegal override code. It declares a checked exception not defined by superclass version.

3. public void eat(String food) {} - A legal overload , not an override , because the argument list changed.

4.  public String eat() {} - Not an override because of the return type, not an overload either because there's no change in the argument list.

Advantages of Using @Override Annotation in the Code

According to Oracle docs,

@Override annotation informs the compiler that the element is meant to override an element declared in a superclass.

   // mark method as a superclass method
// that has been overridden
@Override
int overriddenMethod() { }

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

Overloading vs Overriding

I have already shared the difference between Method Overloading and Method Overriding. Please check it out here.


Overloading vs Overriding

















1. Overloading is an example of compile time polymorphism while Overriding is an example of run time polymorphism.

2. In method overloading parameters must be different. In overriding parameters must be same (different if covariant return type).

3. Method overloading increases the readability of the program. Meanwhile, method overriding provides specific implementation of the method.

More Questions To Test Your Knowledge about Method Overriding

Q1

class Clidder {
private final void flipper() {
System.out.println("Clidder");
}
}
public class Clidlet extends Clidder {
public final void flipper() {
System.out.println("Clidlet");
}
public static void main(String [] args) {
new Clidlet().flipper();
}
}

Answer : Clidlet

Although a final method can not be overridden, in the above case the method is private and therefore hidden. The effect is that a new, accessible method flipper is created.

Q2

public class Tenor extends Singer { 
public static String sing() {
return "fa";

}
public static void main(String[] args) {
Tenor t = new Tenor();
Singer s = new Tenor();
System.out.println(t.sing() + " " + s.sing());
}
}
class Singer {
public static String sing() {
return "la";
}
}

Answer : fa la

The code is correct, but polymorphism doesn't apply to static methods.

Please mention in the comments if you have any questions regarding method overriding in java.


This post first appeared on Java Hungry, please read the originial post: here

Share the post

Method Overriding in Java with Examples

×

Subscribe to Java Hungry

Get updates delivered right to your inbox!

Thank you for your subscription

×