Overriding in Java Programming

Overriding in Java is an object-oriented feature in Java that allows a child class to provide its own implementation (instructions) of a method that is declared in the parent class.

Method overriding in Java, a powerful feature of object-oriented programming, is the process of redefining a method of superclass by the subclass. It allows you to customize a particular feature of an object of superclass, just like modifying the steering feature in a car to suit a specific driving style.

Let’s consider a practical example. We have a superclass ‘Car’ with a method steering(). Imagine we have a subclass ‘Ford’ that extends ‘Car’. In this scenario, the steering() method in ‘Ford’ can override to achieve automation, which may differ from the steering() method in ‘Car’. It’s important to note that the methods specified in the subclass are already present in the superclass, forming a hierarchical relationship. 

The superclass is defined before it is in the subclass. Overriding allows the subclass to implement superclass method, whose implementation may differ from the one in the superclass.

In the example below, the Car class’s steering() method refers to normal steering. Although the subclass, the Ford class, inherits the method from its parent class, the Car class, it overrides the steering() method with its own implementation (instructions). Thus, the Ford uses automatic steering, while the Car uses manual steering.


class Car {
    void steering() {
        System.out.println("Car uses manual steering.");
    }
}

class Ford extends Car {
    @Override
    void steering() {
        System.out.println("Ford uses automated steering.");
    }
}

public class Main {
    public static void main(String[] args) {
        Ford f = new Ford();
        f.steering();
    }
}

Output

Ford uses automated steering.
What is Overriding in Java?

Explanation of the Above Example:

1) Car (Superclass): The superclass, Car, contains a steering() method.

2) Ford (subclass): The Ford class inherits from the superclass Car.

How does the Ford class inherit the steering() method of the superclass? By using the keyword “extends”.

3) Method Overriding: Although the subclass uses the same method name and parameters as its superclass, Car, it defines its own implementation of the steering method.

4) Object Creation: It is another important step for a Java program; the programmer is creating an object for the Ford class. So, it includes Ford f = new Ford();.

5) Method Calling: While executing f.steering(), Java calls the Ford class’s steering() method and displays the message, “Ford uses automated steering”.

Overriding means the ability of a child class to provide its own version of a method that it inherits from the parent class. The method name and parameters must be the same in the parent class and the child class, but the instructions inside the method can differ.

The superclass is also known as the parent class; likewise, the subclass is known as the child class.

For example, in the above code, the void steering() method is the same for the Car class and the Ford class. The parentheses () after steering are empty for both. However, the instructions in the method body can differ. From the example, System.out.println(“Car uses manual steering.”); while the child class, Ford, uses System.out.println(“Ford uses automated steering.”);. With this exception, the child class can change its behavior, which can differ from its parent class requirements.

Inheritance is another important object-oriented feature of Java. Through inheritance, the subclass can implement method overriding. Through method overriding, the subclass can override methods inherited from the superclass. It can override those methods with its own implementation.

Let’s have a brief overview of the topic inheritance to enable the understanding of over-riding.

There are different types of inheritance in programming languages.

They include the following,

1. Simple Inheritance

2. Multiple Inheritance

3. Multi-Level Inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance

Note: Java prohibits extending multiple classes, although a class can implement multiple interfaces.

Method overriding needs an inheritance relationship: a subclass must extend a superclass. It also works across multiple levels, such as C extending B and B extending A.

In simple inheritance,

Class B extends class A.

When B extends (inherits) A;

The meaning of Class B extends Class A is that sub-class B can access all properties of class A.

However, one condition is that it cannot access A’s private properties.

Superclass A cannot access any of the local properties of subclass B.

class A
{
int x;
float y;
public void calculate(int x, float y) {
System.out.println("sum : "+(x+y));
}
}
class B extends A
{
public void calculate(int x, float y) {
System.out.println("Product : "+(x*y));
}
public void display() {
System.out.println("x Value : "+x);
System.out.println("y Value : "+y);
}
public static void main(String args[])
{
A a = new A();
a.calculate (5, 5.5f); // Super-class method
// a.display(); // Error: Super-class cannot access sub-class properties
System.out.println("----------------------");
B b = new B();
b.calculate (7, 7.5f); // Overriding method in sub class
b.display(); // No error
System.out.println("-----------------------");
A a1 = new B();
a1.calculate(9, 9.5f); // Sub-class overriding method
// a1.display(); // Error : Super-class reference cannot access sub-class properties
}
}

Output

sum : 10.5
----------------------
Product : 52.5
x Value : 0
y Value : 0.0
-----------------------
Product : 85.5

Now that you have seen method overriding in code format, here are the rules Java requires an overriding method to follow.

The first requisite is that both the method name and parameter list must be the same for the superclass and subclass.

For example: Ford’s steering() matches the method name of Car’s steering() with no parameters; hence, it can override.

Second, the return type of the child class should match that of the parent class, or its subclass.

class Car {
Car steering() {
System.out.println("Car uses manual steering.");
return new Car();
}
}
class Ford extends Car {
@Override
Ford steering() {
System.out.println("Ford uses automated steering.");
return new Ford();
}
}

In the example above, the Car class’s return type is Car, and the Ford class’s return type is Ford.

Here, although the child class’s return type is Ford, it is a subclass of Car. Thus, Java allows overriding methods to return the same type (Car) or its subclass (Ford).

Thirdly, Access cannot be more restrictive.

When a child class overrides its parent class method, it cannot reduce that method’s accessibility. In simple terms, the overriding method or child method should have either a broader or the same access level as the parent class method.

Both methods below use public access.

class Car {
public void steering() {
System.out.println("Car uses manual steering.");
}
}
class Ford extends Car {
@Override
public void steering() {
System.out.println("Ford uses automated steering.");
}
}

The overriding method can either retain the accessibility level of the parent class or widen it, but is not allowed to narrow it. In terms of accessibility, the narrowest is private, next is default (with no keyword), then protected, and the widest is public. So, if the method in the parent method is default, the child can be default, protected, or public. If the parent method is protected, the child can be either protected or public. If the parent method is public, then the child must compulsorily be public.

Fourthly, the Overriding Method Cannot Throw Broader Checked Exceptions.
Fifthly, including the @Override annotation is not compulsory; it is recommended to include it in a child class while overriding a method.

Another important rule is that the overriding concept only works for inherited methods. Some methods cannot be overridden; the list below includes a detailed description.

private method: Cannot override. (Private methods are not inherited.)
final method: Cannot override. (The compiler reports an error)
static method: Cannot override. (It is hidden)
Constructor: Cannot override. (Constructors are not inherited)

Finally, include super to run the parent class version from inside the overriding method.

Polymorphism in Java, a fundamental and crucial concept, can be best understood through a relatable example. Imagine an object’s ability to take on many forms. Take the example of car’s steering. Every car has a steering system, and the driver does the same thing in each: turn the wheel. But a car with manual steering and a Ford with automated steering respond differently. The action is the same, and the behavior depends on the kind of car.

Polymorphism in Java works the same way. One method call can behave differently depending on the object it is called on.

Car c = new Ford(); // parent reference, child object
c.steering(); // prints: Ford uses automated steering.

The word polymorphism means “many forms.” In Java, the same method name can produce different results, depending on the object or the arguments.

With overloading, the compiler picks the method from the arguments. With overriding, the JVM picks the method at runtime from the object’s actual type.

There are two types of polymorphisms in Java.

They include,

1) Runtime Polymorphism, and

2) Compile Time Polymorphism.

Prepare for interviews with our Java interview questions.

Continue learning:

Previous: Inheritance in Java | Next: Interface in Java Programming | Back to Java Programming

Leave a Comment