BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Method overriding in java with example

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

Declaring a method in sub class which is already present in parent class is known as method overriding. Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class. In this case the method in parent class is called overridden method and the method in child class is called overriding method. In this guide, we will see what is method overriding in Java and why we use it.

Method Overriding Example

Lets take a simple example to understand this. We have two classes: A child class Boy and a parent class Human. The 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 eat() method.

The purpose of Method Overriding is clear here. Child class wants to give its own implementation so that when it calls this method, it prints Boy is eating instead of Human is eating.

class Human{
   //Overridden method
   public void eat()
   {
      System.out.println("Human is eating");
   }
}
class Boy extends Human{
   //Overriding method
   public void eat(){
      System.out.println("Boy is eating");
   }
   public static void main( String args[]) {
      Boy obj = new Boy();
      //This will call the child class version of eat()
      obj.eat();
   }
}

Output:

Boy is eating

Advantage of method overriding

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 code.

This is helpful when a class has several child classes, so if a child class needs to use the parent class method, it can use it and the other classes that want to have different implementation can use overriding feature to make changes without touching the parent class code.

Method Overriding and Dynamic Method Dispatch

Method Overriding is an example of runtime polymorphism. When a parent class reference points to the child class object then the call to the overridden method is determined at runtime, because during method call which method(parent class or child class) is to be executed is determined by the type of object. This process in which call to the overridden method is resolved at runtime is known as dynamic method dispatch. Lets see an example to understand this:

class ABC{
   //Overridden method
   public void disp()
   {
	System.out.println("disp() method of parent class");
   }	   
}
class Demo extends ABC{
   //Overriding method
   public void disp(){
	System.out.println("disp() method of Child class");
   }
   public void newMethod(){
	System.out.println("new method of child class");
   }
   public static void main( String args[]) {
	/* When Parent class reference refers to the parent class object
	 * then in this case overridden method (the method of parent class)
	 *  is called.
	 */
	ABC obj = new ABC();
	obj.disp();

	/* When parent class reference refers to the child class object
	 * then the overriding method (method of child class) is called.
	 * This is called dynamic method dispatch and runtime polymorphism
	 */
	ABC obj2 = new Demo();
	obj2.disp();
   }
}

Output:

disp() method of parent class
disp() method of Child class

In the above example the call to the disp() method using second object (obj2) is runtime polymorphism (or dynamic method dispatch).
Note: In dynamic method dispatch the object can call the overriding methods of child class and all the non-overridden methods of base class but it cannot call the methods which are newly declared in the child class. In the above example the object obj2 is calling the disp(). However if you try to call the newMethod() method (which has been newly declared in Demo class) using obj2 then you would give compilation error with the following message:

Exception in thread "main" java.lang.Error: Unresolved compilation 
problem: The method xyz() is undefined for the type ABC

Rules of method overriding in Java

  1. Argument list: The argument list of overriding method (method of child class) must match the Overridden method(the method of parent class). The data types of the arguments and their sequence should exactly match.
  2. Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class. For e.g. if the Access Modifier of parent class method is public then the overriding method (child class method ) cannot have private, protected and default Access modifier,because all of these three access modifiers are more restrictive than public.
    For e.g. This is not allowed as child class disp method is more restrictive(protected) than base class(public)

    class MyBaseClass{
       public void disp()
       {
           System.out.println("Parent class method");
       }
    }
    class MyChildClass extends MyBaseClass{
       protected void disp(){
          System.out.println("Child class method");
       }
       public static void main( String args[]) {
          MyChildClass obj = new MyChildClass();
          obj.disp();
       }
    }

    Output:

    Exception in thread "main" java.lang.Error: Unresolved compilation 
    problem: Cannot reduce the visibility of the inherited method from MyBaseClass

    However this is perfectly valid scenario as public is less restrictive than protected. Same access modifier is also a valid one.

    class MyBaseClass{
       protected void disp()
       {
           System.out.println("Parent class method");
       }
    }
    class MyChildClass extends MyBaseClass{
       public void disp(){
          System.out.println("Child class method");
       }
       public static void main( String args[]) {
          MyChildClass obj = new MyChildClass();
          obj.disp();
       }
    }

    Output:

    Child class method
  3. private, static and final methods cannot be overridden as they are local to the class. However static methods can be re-declared in the sub class, in this case the sub-class method would act differently and will have nothing to do with the same static method of parent class.
  4. Overriding method (method of child class) can throw unchecked exceptions, regardless of whether the overridden method(method of parent class) throws any exception or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. We will discuss this in detail with example in the upcoming tutorial.
  5. Binding of overridden methods happen at runtime which is known as dynamic binding.
  6. If a class is extending an abstract class or implementing an interface then it has to override all the abstract methods unless the class itself is a abstract class.

Super keyword in Method Overriding

The super keyword is used for calling the parent class method/constructor. super.myMethod() calls the myMethod() method of base class while super() calls the constructor of base class. Let’s see the use of super in method Overriding.
As we know that we we override a method in child class, then call to the method using child class object calls the overridden method. By using super we can call the overridden method as shown in the example below:

class ABC{
   public void myMethod()
   {
	System.out.println("Overridden method");
   }	   
}
class Demo extends ABC{
   public void myMethod(){
	//This will call the myMethod() of parent class
	super.myMethod();
	System.out.println("Overriding method");
   }
   public static void main( String args[]) {
	Demo obj = new Demo();
	obj.myMethod();
   }
}

Output:

Class ABC: mymethod()
Class Test: mymethod()

As you see using super keyword, we can access the overriden method.

❮ PreviousNext ❯

Top Related Articles:

  1. Final Keyword In Java – Final variable, Method and Class
  2. Multithreading in java with examples
  3. User defined exception in java
  4. Packages in Java explained with Examples
  5. Java – Static Class, Block, Methods and Variables

Tags: Java-OOPs

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Furqan Hussain says

    September 10, 2014 at 5:52 AM

    Hi Dear,

    Although i have visited may sites to learn java programming but the concept and explanation giving by example on your side never seen anywhere else.

    I need you cooperation to learn java.

    Pls Help.
    Thanks.

    Reply
  2. tahir says

    September 16, 2014 at 10:50 AM

    can we call the non overridden methods of base class in dynamic method dispatch with the base class reference to which the child class object is assign?

    Reply
    • Chaitanya Singh says

      September 20, 2014 at 7:45 AM

      Yes we can.

      Reply
      • Owais says

        December 12, 2014 at 3:57 PM

        nice work , i appriciate it.

        Reply
  3. Amit Gupta says

    November 12, 2014 at 11:27 AM

    https://beginnersbook.com/2014/01/method-overriding-in-java-with-example/

    Rules of method overriding in Java
    Point 2 need to be corrected from Return Type to Access Modifier

    Reply
  4. Sachindra says

    November 28, 2014 at 9:46 AM

    I called Newly created Method xyz() of child class,but its running perfectly..i does not give any error as you said it will throw
    Exception in thread “main” java.lang.Error: Unresolved compilation
    problem: The method xyz() is undefined for the type ABC

    Reply
    • Dave says

      July 31, 2015 at 12:33 PM

      Then you did something wrong, because it shouldn’t work. At compile time the object is static bound to the base class and it will not find a method xyz() in the base class.

      Reply
  5. janardhan reddy says

    April 4, 2015 at 6:05 AM

    I’ve visited so many sites but this site for learning java is exceptionally well
    i hope everybody can understand and learn java easily.surly i need a help from your side is in depth about static keyword and object .how object stores memory and how method behaves on object

    Reply
  6. sandhana lakshmi says

    September 6, 2015 at 6:07 AM

    why we cannot override constructors?

    Reply
    • Prakash says

      December 8, 2015 at 6:27 PM

      1) NO! A constructor belongs to the class in which it is declared. A sub class is a different class and must have its own constructor. So, constructors simply can’t be overridden.

      2) Yes, that’s done usually in case of singletons.

      Reply
    • laxman says

      March 17, 2016 at 11:20 AM

      We can’t override s constructor because if we try to override the constructor in another class then it will be considered as a method in that class.

      Reply
  7. Roman says

    November 29, 2015 at 11:28 AM

    Can you explain this please?
    ABC obj = new Test();
    When I need construction like this if I can do:
    Test obj = new Test();
    To call all methods I want.Thank you!

    Reply
    • naveen says

      June 12, 2016 at 3:59 AM

      this is an upcasting

      Reply
  8. Gayathri says

    January 5, 2016 at 3:16 PM

    Nice work..clearly explained the nook and corner of the chapter..

    Reply
  9. Learner says

    April 20, 2016 at 5:37 AM

    Can we change the return type while overriding a method ?

    Reply
    • Ketan says

      August 6, 2016 at 4:52 AM

      Yes we can change but, return type can be either same or sub type of the super class method return type that is called as a covariance (introduced from java 1.5)

      Reply
      • kalpana says

        April 24, 2024 at 11:45 PM

        no we can not change if we change the return type of parameter then we will get compile time error in method overloading we have change the parameter but it must same method name .
        in method overridding we don’t change datatype ,return type and sequence of parameter it should be as super class but we just change logic/implimentation

        Reply
  10. maryam says

    May 10, 2016 at 6:05 AM

    I called a new method of ChidClass (xyz())
    but It Worked Perfectly and this Exception you said not happened
    Exception in thread “main” java.lang.Error: Unresolved compilation
    problem: The method xyz() is undefined for the type ABC

    Reply
  11. natwar says

    November 25, 2016 at 5:57 AM

    Examples illustrated are very simple and easy to understand and covers all the basic requirements.Please keep updating your posts.

    Reply
  12. Raju says

    January 13, 2017 at 4:45 AM

    Hey, lovee your work, but I would like to make a suggestion, please add a ‘next chapter’ or next botton at the end so we can continue to the next article of this post or any post, it would be helpful

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap