Method Overriding in Java
Method overriding is a fundamental concept in Java's object-oriented programming. It allows a subclass to provide a specific implementation of a method that is already defined in its superclass. When you override a method, you replace the inherited implementation in the superclass with your own implementation in the subclass. This is used to achieve polymorphism and dynamic method dispatch.
Here are the key points to remember when overriding a method in Java:
1. Method Signature: When you override a method, the method name, return type, and number and type of parameters must be exactly the same as the method in the superclass. The
@Override
annotation is often used to indicate that a method is intended to override a superclass method.2. Access Modifier: The access level of the overriding method cannot be more restrictive than the overridden method. It can be the same or less restrictive, but not more restrictive. For example, you can't override a
public
method with aprivate
one.3. Exception Handling: The overriding method can throw the same, subclass, or no exceptions compared to the overridden method. It cannot throw broader exceptions or new checked exceptions that are not compatible with the overridden method's exceptions.
Here's an example illustrating method overriding in Java:
In this example, car is a subclass of Vehicle, and it overrides the speed method. When we create a car object and call speed on it, it calls the car class's speed method instead of the Vehicle class's implementation. This behavior is called dynamic method dispatch, and it's a fundamental feature of polymorphism in Java.
Method overriding is essential for creating a flexible and extensible class hierarchy in object-oriented programming, as it allows subclasses to provide specialized behavior while maintaining a common interface defined in the superclass.
It is done in IntelliJ so Override annotation show automatically and it show car method i.e. (good speed done) message.
public class FinalDemo {
public static void main(String[] args) {
Vehicle fd=new car();
fd.speed();
}
}
class Vehicle
{
void speed()
{
System.out.println("good speed");
}
}
class car extends Vehicle
{
void speed()
{
System.out.println("good speed done");
}
}