The Wayback Machine - https://web.archive.org/web/20240921073551/https://www.geeksforgeeks.org/overriding-in-java/
Open In App

Overriding in Java

Last Updated : 01 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java, 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, the same parameters or signature, and the 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.

Method Overriding in Java

Method overriding is one of the ways by which Java achieves Run Time Polymorphism. The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.

Example of Method Overriding in Java

Below is the implementation of the Java Method Overriding:

Java




// Java program to demonstrate
// method overriding in java
 
// Base Class
class Parent {
    void show() { System.out.println("Parent's show()"); }
}
 
// Inherited class
class Child extends Parent {
    // This method overrides show() of Parent
    @Override void show()
    {
        System.out.println("Child's show()");
    }
}
 
// Driver class
class Main {
    public static void main(String[] args)
    {
        // If a Parent type reference refers
        // to a Parent object, then Parent's
        // show is called
        Parent obj1 = new Parent();
        obj1.show();
 
        // If a Parent type reference refers
        // to a Child object Child's show()
        // is called. This is called RUN TIME
        // POLYMORPHISM.
        Parent obj2 = new Child();
        obj2.show();
    }
}


Output

Parent's show()
Child's show()

Rules for Java Method Overriding

1. Overriding and Access Modifiers

The access modifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass. Doing so will generate a compile-time error. 

Java




// A Simple Java program to demonstrate
// Overriding and Access-Modifiers
 
class Parent {
    // private methods are not overridden
    private void m1()
    {
        System.out.println("From parent m1()");
    }
 
    protected void m2()
    {
        System.out.println("From parent m2()");
    }
}
 
class Child extends Parent {
    // new m1() method
    // unique to Child class
    private void m1()
    {
        System.out.println("From child m1()");
    }
 
    // overriding method
    // with more accessibility
    @Override public void m2()
    {
        System.out.println("From child m2()");
    }
}
 
// Driver class
class Main {
    public static void main(String[] args)
    {
        Parent obj1 = new Parent();
        obj1.m2();
        Parent obj2 = new Child();
        obj2.m2();
    }
}


Output

From parent m2()
From child m2()

2. Final methods can not be overridden

If we don’t want a method to be overridden, we declare it as final. Please see Using Final with Inheritance. 

Java




// A Java program to demonstrate that
// final methods cannot be overridden
 
class Parent {
    // Can't be overridden
    final void show() {}
}
 
class Child extends Parent {
    // This would produce error
    void show() {}
}


Output

13: error: show() in Child cannot override show() in Parent
void show() { }
^
overridden method is final

3. Static methods can not be overridden(Method Overriding vs Method Hiding): 

When you define a static method with the same signature as a static method in the base class, it is known as method hiding. The following table summarizes what happens when you define a method with the same signature as a method in a super-class.

  Superclass Instance Method Superclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides

Java




// Java program to show that
// if the static method is redefined by
// a derived class, then it is not
// overriding, it is hiding
 
class Parent {
    // Static method in base class
    // which will be hidden in subclass
    static void m1()
    {
        System.out.println("From parent "
                           + "static m1()");
    }
 
    // Non-static method which will
    // be overridden in derived class
    void m2()
    {
        System.out.println(
            "From parent "
            + "non - static(instance) m2() ");
    }
}
 
class Child extends Parent {
    // This method hides m1() in Parent
    static void m1()
    {
        System.out.println("From child static m1()");
    }
 
    // This method overrides m2() in Parent
    @Override public void m2()
    {
        System.out.println(
            "From child "
            + "non - static(instance) m2() ");
    }
}
 
// Driver class
class Main {
    public static void main(String[] args)
    {
        Parent obj1 = new Child();
 
        // As per overriding rules this
        // should call to class Child static
        // overridden method. Since static
        // method can not be overridden, it
        // calls Parent's m1()
        obj1.m1();
 
        // Here overriding works
        // and Child's m2() is called
        obj1.m2();
    }
}


Output

From parent static m1()
From child non - static(instance) m2() 

4. Private methods can not be overridden

Private methods cannot be overridden as they are bonded during compile time. Therefore we can’t even override private methods in a subclass.(See this for details).

Java




class SuperClass {
    private void privateMethod()
    {
        System.out.println(
            "This is a private method in SuperClass");
    }
 
    public void publicMethod()
    {
        System.out.println(
            "This is a public method in SuperClass");
        privateMethod();
    }
}
 
class SubClass extends SuperClass {
    // This is a new method with the same name as the
    // private method in SuperClass
    private void privateMethod()
    {
        System.out.println(
            "This is a private method in SubClass");
    }
 
    // This method overrides the public method in SuperClass
    public void publicMethod()
    {
        System.out.println(
            "This is a public method in SubClass");
        privateMethod(); // calls the private method in
                         // SubClass, not SuperClass
    }
}
 
public class Test {
    public static void main(String[] args)
    {
        SuperClass obj1 = new SuperClass();
        obj1.publicMethod(); // calls the public method in
                             // SuperClass
 
        SubClass obj2 = new SubClass();
        obj2.publicMethod(); // calls the overridden public
                             // method in SubClass
    }
}


Output

This is a public method in SuperClass
This is a private method in SuperClass
This is a public method in SubClass
This is a private method in SubClass

5. The overriding method must have the same return type (or subtype)

From Java 5.0 onwards it is possible to have different return types for an overriding method in the child class, but the child’s return type should be a sub-type of the parent’s return type. This phenomenon is known as the covariant return type.

Java




class SuperClass {
    public Object method()
    {
        System.out.println(
            "This is the method in SuperClass");
        return new Object();
    }
}
 
class SubClass extends SuperClass {
    public String method()
    {
        System.out.println(
            "This is the method in SubClass");
        return "Hello, World!";
    }
}
 
public class Test {
    public static void main(String[] args)
    {
        SuperClass obj1 = new SuperClass();
        obj1.method();
 
        SubClass obj2 = new SubClass();
        obj2.method();
    }
}


Output

This is the method in SuperClass
This is the method in SubClass

6. Invoking overridden method from sub-class

We can call the parent class method in the overriding method using the super keyword. 

Java




// A Java program to demonstrate that overridden
// method can be called from sub-class
 
// Base Class
class Parent {
    void show() { System.out.println("Parent's show()"); }
}
 
// Inherited class
class Child extends Parent {
    // This method overrides show() of Parent
    @Override void show()
    {
        super.show();
        System.out.println("Child's show()");
    }
}
 
// Driver class
class Main {
    public static void main(String[] args)
    {
        Parent obj = new Child();
        obj.show();
    }
}


Output

Parent's show()
Child's show()

Overriding and Constructor

We can not override the constructor as the parent and child class can never have a constructor with the same name(The constructor name must always be the same as the Class name).

Overriding and Exception-Handling

Below are two rules to note when overriding methods related to exception handling.

Rule #1

If the super-class overridden method does not throw an exception, the subclass overriding method can only throw the unchecked exception, throwing a checked exception will lead to a compile-time error. 

Java




// Java program to demonstrate overriding when
// superclass method does not declare an exception
 
class Parent {
    void m1() { System.out.println("From parent m1()"); }
 
    void m2() { System.out.println("From parent  m2()"); }
}
 
class Child extends Parent {
    @Override
    // no issue while throwing unchecked exception
    void m1() throws ArithmeticException
    {
        System.out.println("From child m1()");
    }
 
    @Override
    // compile-time error
    // issue while throwing checked exception
    void m2() throws Exception
    {
        System.out.println("From child m2");
    }
}


Output

error: m2() in Child cannot override m2() in Parent
void m2() throws Exception{ System.out.println("From child m2");}
^
overridden method does not throw Exception

Rule #2

If the superclass overridden method does throw an exception, the subclass overriding method can only throw the same, subclass exception. Throwing parent exceptions in the Exception hierarchy will lead to compile time error. Also, there is no issue if the subclass overridden method is not throwing any exception. 

Java




// Java program to demonstrate overriding when
// superclass method does declare an exception
 
class Parent {
    void m1() throws RuntimeException
    {
        System.out.println("From parent m1()");
    }
}
 
class Child1 extends Parent {
    @Override
    // no issue while throwing same exception
    void m1() throws RuntimeException
    {
        System.out.println("From child1 m1()");
    }
}
class Child2 extends Parent {
    @Override
    // no issue while throwing subclass exception
    void m1() throws ArithmeticException
    {
        System.out.println("From child2 m1()");
    }
}
class Child3 extends Parent {
    @Override
    // no issue while not throwing any exception
    void m1()
    {
        System.out.println("From child3 m1()");
    }
}
class Child4 extends Parent {
    @Override
    // compile-time error
    // issue while throwing parent exception
    void m1() throws Exception
    {
        System.out.println("From child4 m1()");
    }
}


Output

error: m1() in Child4 cannot override m1() in Parent
void m1() throws Exception
^
overridden method does not throw Exception

Overriding and Abstract Method

Abstract methods in an interface or abstract class are meant to be overridden in derived concrete classes otherwise a compile-time error will be thrown.

Overriding and Synchronized/strictfp Method

The presence of a synchronized/strictfp modifier with the method has no effect on the rules of overriding, i.e. it’s possible that a synchronized/strictfp method can override a non-synchronized/strictfp one and vice-versa.

Note:

  1. In C++, we need virtual keyword to achieve overriding or Run Time Polymorphism. In Java, methods are virtual by default.
  2. We can have multilevel method-overriding. 

Java




// A Java program to demonstrate
// multi-level overriding
 
// Base Class
class Parent {
    void show() { System.out.println("Parent's show()"); }
}
 
// Inherited class
class Child extends Parent {
    // This method overrides show() of Parent
    void show() { System.out.println("Child's show()"); }
}
 
// Inherited class
class GrandChild extends Child {
    // This method overrides show() of Parent
    void show()
    {
        System.out.println("GrandChild's show()");
    }
}
 
// Driver class
class Main {
    public static void main(String[] args)
    {
        Parent obj1 = new GrandChild();
        obj1.show();
    }
}


Output

GrandChild's show()

Method Overriding vs Method Overloading

1. Overloading is about the same method having different signatures. Overriding is about the same method, and same signature but different classes connected through inheritance. 

Method Overloading vs Method Overriding

2. Overloading is an example of compiler-time polymorphism and overriding is an example of run-time polymorphism.

FAQs on Java Method Overriding

Q1. What is Method Overriding?

As stated earlier, overridden methods allow Java to support run-time polymorphism. Polymorphism is essential to object-oriented programming for one reason: it allows a general class to specify methods that will be common to all of its derivatives while allowing subclasses to define the specific implementation of some or all of those methods. Overridden methods are another way that Java implements the “one interface, multiple methods” aspect of polymorphism. Dynamic Method Dispatch is one of the most powerful mechanisms that object-oriented design brings to bear on code reuse and robustness. The ability to exist code libraries to call methods on instances of new classes without recompiling while maintaining a clean abstract interface is a profoundly powerful tool. Overridden methods allow us to call methods of any of the derived classes without even knowing the type of derived class object.  

Q2. When to apply Method Overriding? (with example)

Overriding and Inheritance: Part of the key to successfully applying polymorphism is understanding that the superclasses and subclasses form a hierarchy that moves from lesser to greater specialization. Used correctly, the superclass provides all elements that a subclass can use directly. It also defines those methods that the derived class must implement on its own. This allows the subclass the flexibility to define its methods, yet still enforces a consistent interface. Thus, by combining inheritance with overridden methods, a superclass can define the general form of the methods that will be used by all of its subclasses. Let’s look at a more practical example that uses method overriding. Consider an employee management software for an organization, let the code has a simple base class Employee, and the class has methods like raiseSalary(), transfer(), promote(), .. etc. Different types of employees like Manager, Engineer, ..etc may have their implementations of the methods present in base class Employee. In our complete software, we just need to pass a list of employees everywhere and call appropriate methods without even knowing the type of employee. For example, we can easily raise the salary of all employees by iterating through the list of employees. Every type of employee may have its logic in its class, we don’t need to worry because if raiseSalary() is present for a specific employee type, only that method would be called. 

 

Java Overriding

 

Java




// Java program to demonstrate application
// of overriding in Java
 
// Base Class
class Employee {
    public static int base = 10000;
    int salary() { return base; }
}
 
// Inherited class
class Manager extends Employee {
    // This method overrides salary() of Parent
    int salary() { return base + 20000; }
}
 
// Inherited class
class Clerk extends Employee {
    // This method overrides salary() of Parent
    int salary() { return base + 10000; }
}
 
// Driver class
class Main {
    // This method can be used to print the salary of
    // any type of employee using base class reference
    static void printSalary(Employee e)
    {
        System.out.println(e.salary());
    }
 
    public static void main(String[] args)
    {
        Employee obj1 = new Manager();
 
        // We could also get type of employee using
        // one more overridden method.loke getType()
        System.out.print("Manager's salary : ");
        printSalary(obj1);
 
        Employee obj2 = new Clerk();
        System.out.print("Clerk's salary : ");
        printSalary(obj2);
    }
}


Output

Manager's salary : 30000
Clerk's salary : 20000

Related Article



Previous Article
Next Article

Similar Reads

Exception Handling with Method Overriding in Java
An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-oriented programming language, Overriding is a feature t
6 min read
Different Ways to Prevent Method Overriding in Java
Inheritance is a substantial rule of any Object-Oriented Programming (OOP) language but still, there are ways to prevent method overriding in child classes which are as follows: Methods: Using a static methodUsing private access modifierUsing default access modifierUsing the final keyword method Method 1: Using a static method This is the first way
5 min read
Java - Covariant Method Overriding with Examples
The covariant method overriding approach, implemented in Java 5, helps to remove the client-side typecasting by enabling you to return a subtype of the overridden method's actual return type. Covariant Method overriding means that when overriding a method in the child class, the return type may vary. Before java 5 it was not allowed to override any
4 min read
When We Need to Prevent Method Overriding in Java ?
Here we will be discussing why should we prevent method overriding in java. So, before going into the topic, let's give a look at the below important concept then we will move to the actual topic. As we know Object Oriented Programming (OOPs) concept consists of 4 important concepts that are as follows: EncapsulationInheritancePolymorphismAbstracti
4 min read
Variables in Java Do Not Follow Polymorphism and Overriding
Variables in Java do not follow polymorphism. Overriding is only applicable to methods but not to variables. In Java, if the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable, even if their types are different. This concept is known as Variable Hiding. In the case of method over
2 min read
Overriding equals method in Java
Consider the following Java program: Java Code class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; } } // Driver class to test the Complex class public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); Complex c2 = new Complex(10, 15); if (c1 == c2) { System
3 min read
Overriding toString() Method in Java
Java being object-oriented only deals with classes and objects so do if we do require any computation we use the help of object/s corresponding to the class. It is the most frequent method of Java been used to get a string representation of an object. Now you must be wondering that till now they were not using the same but getting string representa
3 min read
Output of Java program | Set 18 (Overriding)
Prerequisite - Overriding in Java 1) What is the output of the following program? class Derived { protected final void getDetails() { System.out.println("Derived class"); } } public class Test extends Derived { protected final void getDetails() { System.out.println("Test class"); } public static void main(String[] args) { Derive
3 min read
Overriding methods from different packages in Java
Prerequisite : Overriding in Java, Packages in Java Packages provide more layer of encapsulation for classes. Thus, visibility of a method in different packages is different from that in the same package. How JVM find which method to call? When we run a java program, JVM checks the runtime class of the object. JVM checks whether the object's runtim
3 min read
Difference Between Method Overloading and Method Overriding in Java
The differences between Method Overloading and Method Overriding in Java are as follows: Method Overloading Method Overriding Method overloading is a compile-time polymorphism.Method overriding is a run-time polymorphism.Method overloading helps to increase the readability of the program.Method overriding is used to grant the specific implementatio
4 min read
Method Overriding with Access Modifier
Prerequisites: Method Overriding in java and Access Modifier in Java Method Overriding 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 its super-class or parent class. When a method in a subclass has the same name,
3 min read
Overriding of Thread class start() method
Whenever we override start() method then our start() method will be executed just like a normal method call and new thread wont be created. We can override start/run method of Thread class because it is not final. But it is not recommended to override start() method, otherwise it ruins multi-threading concept. // Java program illustrate the concept
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Article Tags :
Practice Tags :