Junior — Middle
Can you explain the concept of method overriding in Java?
sobes.tech AI
Answer from AI
Method overriding in Java is a mechanism that allows a subclass to provide its own implementation of a method that is already defined in the superclass.
Main points:
- The method in the subclass must have the same signature (name, parameters) and return type (or a compatible one).
- The access modifier cannot be more restrictive than that of the superclass method.
- It enables polymorphism: when calling a method through a reference to the superclass, the subclass's method will be invoked.
Example:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
animal.sound(); // Will output "Bark"
}
}
Here, the sound method is overridden in the Dog class, allowing the behavior to be changed.