


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Method Overriding is a way to realize Polymorphism in Java. In this tutorial, we shall learn Overriding in Java with Example Programs, where methods of Super Class are overridden by methods of Sub Class. In context of sub-class extending a super-class, the sub-class can access super-class’s methods. If in case the sub-class wants functionality of an existing method in Super Class to be replaced by some specific implementation, then Java provides the ability to override the existing functionality through Method Overriding. It can also be thought of as Runtime Polymorphism.
Following are the rules for implementing Method Overriding in Java.
We shall take an example scenario where Car is a super-class and Audi is a sub-class. Following is the super class. Car.java
public class Car { public void brake(){ System.out.println("break in Car"); } public void accelerate(){ System.out.println("accelerate in Car"); } }
Following is the sub class. Audi.java Run the above program. You shall get the following output in console.
Now we shall override accelerate method in Audi.java by overriding accelerate() in Car.java Car.java Audi.java public class Audi extends Car { public static void main(String[] args) { Audi audi = new Audi(); audi.accelerate(); audi.brake(); } } accelerate in Car break in Car public class Car { public void brake(){ System.out.println("break in Car"); } public void accelerate(){ System.out.println("accelerate in Car"); } } public class Audi extends Car { public static void main(String[] args) { Audi audi = new Audi(); audi.accelerate(); audi.brake(); } public void accelerate(){ System.out.println("accelerate in Audi"); } }
In this Java Tutorial, we have learnt Method Overriding in Java with example programs, the pre-requisites to override a method. In our next tutorial, we shall learn about Final Keyword in Java. Java Tutorial ✦ Java Tutorial ✦ Java Introduction ✦ Java Installation ✦ IDEs for Java Development ✦ Java HelloWorld Program ✦ Java Program Structure ✦ Java Datatypes ✦ Java Variable Types ✦ Java Access Modifiers ✦ Java Operators ✦ Java Decision Making ✦ Java Loops ✦ Java Array ✦ Java OOPs ✦ Java String ✦ Java Exception Handling ✦ Java File Operations ✦ Java Date & Time ✦ Java MySQL ✦ Java Random ✦ Java Math