Overriding in Java
Overriding in Java is a feature that allows a subclass to provide a different implementation of a method that is already defined in its superclass. The overridden method must have the same name, return type, and parameter list as the method in the superclass.
Example 1: Animal Hierarchy
Consider the following hierarchy of animal classes:
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
In this example, the Animal
class has a method named makeSound
that prints a generic sound. The Dog
class extends the Animal
class and overrides the makeSound
method to provide a specific implementation for dogs. When we create an instance of Dog
and invoke the makeSound
method, it prints "The dog barks" instead of the generic sound defined in the Animal
class.
Example 2: Shape Hierarchy
Consider another example where we have a hierarchy of shape classes:
abstract class Shape {
public abstract double calculateArea();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
In this case, the Shape
class is an abstract class with an abstract method calculateArea
. The Circle
class extends the Shape
class and provides an implementation for the calculateArea
method specific to circles. When we create an instance of Circle
and invoke the calculateArea
method, it calculates the area of the circle using the provided formula.
Go To OOPS Page Click Here