Overriding in Java

What is Overriding in Java? 

Overriding is when a child class has its method implementation for the method already present in the parent class.

Technically, overriding is a function that requires a subclass or child class to provide a variety of method implementations, that are already provided by one of its superclasses or parent classes, in any object-oriented programming language. 

When a method in a subclass has the same name and signature as in its super-class, the subclass is originated from the super-class. 

One of the ways that Java manages Run Time Polymorphism is by method overriding. 

The object that is used to trigger a method specifies the variant of the process that is executed. If it implements a method with an object from a parent class, the parent class's version will be used. But if the method is triggered with an object from a subclass, the child class's version will be used. 

Example 1:

Code:

// here we declare vehicle as a parent class 

 class Vehicle{

// here we create a method as vehicle has engine

// but changing the output as vehicle engine

void engine(){

System.out.println("this is vehicle engine");

}

}

 // here we declare child class 

 // bike is based on vehicle category so its a child class

 // we use extends keyword to call parent class

 class Bike extends Vehicle{

// here we create method as same as in parent class

// but changing the output as bike engine

void engine(){

System.out.println ("this is bike engine");

}

}

 // here we declare child class 

 // car is based on vehicle category so it's a child class

 class Car extends Vehicle{

// here we create method as same as in parent class

// but changing the output as car engine

void engine(){

System.out.println ("this is car engine");

}

}

public class Code Example {

public static void main(String[] arg) {

// here we create object for bike

Bike honda = new Bike ();

honda.engine();// calling engine method

// here we create object for car

Car benz = new Car ();

benz.engine ();  //calling engine method

}

}

Output:

this is bike engine

this is car engine

In the above code, void engine() within Vehicle class is called overridden method. The void engine() method within Bike Class and Car Class is called the overriding method.

OverridinginJavaEx1_1

OverridinginJavaEx1_2

OverridinginJavaEx1_3

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

Why Is Overriding in Java Useful?

As previously mentioned, overridden methods allow Java to accept polymorphism at runtime. Overridden methods are also another way Java embraces polymorphism's "one application, many methods" aspect.

The most effective object-oriented programming brings to bear on code reuse and robustness is Dynamic Process Execution. The ability to use existing code libraries to call methods on new class instances without re-compiling, while preserving a clean abstract interface, is an incredibly powerful weapon.

 Overridden methods allow one to call methods from any derived class object without identifying the form of the modified super-class.

When Is It Ideal to Apply Overriding in Java?

Identifying the parent classes and child classes form a hierarchy that passes from lesser to higher productivity is part of the secret to effectively applying polymorphism. 

The parent class, when used correctly, contains all the factors that a child class would access directly. It also defines which methods the child class must execute individually.

This provides the child class with the ability to convey its methods while preserving a standard interface. 

A parent class will determine the general form of the methods that are used by all of its child classes by merging inheritance and overridden methods. 

Example 2:

Code:

//creating parent class

class Bank{  

//create function to calculate interest

int getRateOfInterest(){return 0;}  

}  

//Creating child classes.  

class SBI extends Bank{  

//create function to calculate interest for SBI

int getRateOfInterest(){return 8;}  

}  

class ICICI extends Bank{  

//create function to calculate interest for ICICI

int getRateOfInterest(){return 7;}  

}  

class AXIS extends Bank{  

//create function to calculate interest for AXIS

int getRateOfInterest(){return 9;}  

}  

public class CodeExample {

public static void main(String[] arg) {

Bank sbibank=new SBI();  // create object for SBI

Bank icicibank=new ICICI();  // create object for ICICI

Bank axisbank=new AXIS();  // create object for AXIS

System.out.println("SBI Rate of Interest: "+sbibank.getRateOfInterest());  

System.out.println("ICICI Rate of Interest: "+icicibank.getRateOfInterest());  

System.out.println("AXIS Rate of Interest: "+axisbank.getRateOfInterest());  

}

}

Output

SBI Rate of Interest: 8

ICICI Rate of Interest: 7

AXIS Rate of Interest: 9

Screenshot

OverridinginJavaEx2_1

OverridinginJavaEx2_2.

What Are the Rules for Method Overriding in Java? 

Laws of Method Overriding in JAVA: 

  1. The method name should be common and the same as it is in the parent class.
  2. The method signature (parameter list, return type) in the method must be the same as in the parent class.
  3. There must be an inheritance connection between classes.
  4. All the abstract methods in the parent class should be overridden in the child class.
  5. If it declared the methods as static or final, then those methods cannot be overridden.

Handle Access-Modifiers in Overriding:

An overriding method's activities increase will give more access than the overridden method. A protected method in the parent class may be made public but not private in the child class. If you force it to be done, it will cause a compile-time error.

The goal of Approach Overriding in Java is transparent in this situation. The child class has to have its implementation of this process.

Example 3:

Code:

//Overriding and Access-Modifiers 

//here we declare parent class

class Vehicle { 

// private methods are not overridden 

//if we create a function using the final keyword or static keyword word function can't be overridden in child class

private void engine() 

System.out.println("Vehicle engine"); 

protected void fueltype() 

System.out.println("Vehicle fueltype"); 

//here we declare child class

class Car extends Vehicle { 

// unique to Child class 

void engine() 

System.out.println("Car engine"); 

protected void fueltype() 

System.out.println("Car fueltype"); 

public class CodeExample {

public static void main(String[] arg) {

Vehicle vehicle = new Vehicle(); 

vehicle.fueltype(); 

Vehicle benz = new Car(); 

benz.fueltype();

// here we can't call engine type b'coz its private access modifier in parent class

// if we call getting error

}

}

Output:

From parent fuel type

From Car fuel type

Screenshot

OverridinginJavaEx3_1

OverridinginJavaEx3_2

OverridinginJavaEx3_3

For Final methods:

If you declare any method as final, it cannot override it. It is impossible to override final methods.

For Constructor methods:

Obviously, the constructor will have its class name, so it also cannot be overridden.

For Abstract methods:

If the abstract method is in the interface or any other class, the child class should override.

For Static methods:

Similar to the final methods, the static methods also cannot be overridden. The static method in the parent class will be hidden from the child 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

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

Activating an Overridden Method:

The super keyword will be used to invoke the parent class function in an overriding method.

Error Handling in Overriding in JAVA:

There are three ways how overriding deals with exception-handling.

  • When the parent class doesn’t declare an exception, the child class can declare only unchecked exceptions.
  • When the parent class has declared an exception, the child class can declare the same exception, not any other exceptions.
  • When the parent class has declared an exception, the child class can declare without exceptions.

Note: 

  1. To implement overriding or Run Time Polymorphism in C++, you need to use the virtual keyword. Methods are synthetic by nature in Java.
  2. Multilevel process override is feasible.
  3. By overriding, the child class extends the capabilities of the parent class.
  4. Method overriding implements both polymorphism and inheritance for code scalability.
Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Conclusion:

In Java, method overriding occurs when a subclass (child class) has the same method as the parent class. In other words, method overriding occurs when a subclass provides a particular implementation of a method declared by one of its parent classes. The ability for a subclass to override a method allows a class to inherit from a superclass with "near enough" actions and then change it as required. The name, number, and type of parameters, and return type of the overriding method are identical to those of the method it overrides.

If you want to master web application creation for every programming platform, then Simplilearn's Java Certification Training course is for you. This course will provide you with a solid understanding of Java, the most widely used programming language in software development. It's a 60-hour Applied Learning course that explores Hibernate and Spring structures and offers hands-on coding and implementation of two web-based projects.

Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on them, as soon as possible!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.