0% completed
Method overriding is a fundamental concept in Object-Oriented Programming (OOP) that allows a subclass to provide a specific implementation of a method that is already defined in its superclass. This mechanism is a key aspect of runtime polymorphism, enabling Java to decide at runtime which method implementation to execute based on the actual object's type. Method overriding enhances the flexibility and reusability of code by allowing subclasses to modify or extend the behavior of their superclasses.
Method overriding occurs when a subclass provides its own version of a method that is already defined in its superclass. The overridden method in the subclass must have the same name, return type, and parameter list as the method in the superclass.
Runtime Polymorphism: Method overriding facilitates runtime polymorphism, where the method to be invoked is determined during program execution based on the actual object's type, not the reference type.
Purpose: Allows subclasses to tailor or enhance the behavior of inherited methods, promoting code reuse and adhering to the principle of "programming to an interface."
Same Method Signature: The method in the subclass must have the same name, return type, and parameter list as the method in the superclass.
Access Level: The overridden method in the subclass cannot have a more restrictive access modifier than the method in the superclass. For example, a public
method in the superclass cannot be overridden with a protected
or private
method in the subclass.
Non-Static Methods: Only instance methods (non-static methods) can be overridden. Static methods cannot be overridden; they can be hidden instead.
Cannot Override final
Methods: Methods declared as final
in the superclass cannot be overridden by subclasses.
Exceptions: The overriding method can throw fewer or more specific checked exceptions than the overridden method but cannot throw broader or new checked exceptions.
In this example, we'll create a Car
superclass with a displayInfo
method. We'll then create a SportsCar
subclass that overrides the displayInfo
method to provide additional details specific to sports cars. The Solution
class will demonstrate how method overriding works in practice.
Here, which method will be invoked is decided at the run-time based on the instance of the class used to call the method.
Explanation:
Car
Class:
displayInfo
Method: Prints the car's brand, color, and manufacturing year.SportsCar
Class:
displayInfo
Method:
@Override
annotation indicates that this method overrides the superclass method.super.displayInfo()
to call displayInfo()
mehtod of the Car
class and display the common car details.SportsCar
by printing the top speed......
.....
.....