Method overriding in Java allows a subclass to provide a specific implementation of a method that is already defined in its superclass. Method overriding is used to achieve polymorphism, where a subclass can define its behavior while maintaining a common interface. Here's an overview of when and how to use method overriding in Java:
Purpose:
Modify Behavior: Method overriding allows a subclass to modify or extend the behavior of a method inherited from its superclass.
Polymorphism: Method overriding enables polymorphism, where an object of the subclass can be treated as an object of the superclass, providing flexibility and code reuse.
Follows the "IS-A" Relationship: Method overriding is used when a subclass "IS-A" type of its superclass, indicating a specialization or refinement of the superclass behavior.
How to use:
Create a subclass that extends the superclass containing the method to be overridden.
Define a method in the subclass with the same signature (name, return type, and parameters) as the method in the superclass.
Add the @Override annotation to ensure that the method is indeed intended to override a superclass method. While not mandatory, it helps prevent accidental mistakes.
The subclass method must have the same or more permissive access modifier as the superclass method.
Example:
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
// Using method overriding
Shape shape = new Circle(); // Polymorphic assignment
shape.draw(); // Output: "Drawing a circle"
No comments:
Post a Comment