Junior
When is a method considered overridden?
sobes.tech AI
Answer from AI
A method is considered overridden (overriding) in object-oriented programming when:
- It is defined in a subclass with the same name, return type, and parameter list (signature) as the method in the superclass.
- The parent method is not
private. - The subclass method does not have a more restrictive access modifier than the parent method.
- In case of exceptions, the overriding method cannot declare checked exceptions that are broader than those declared in the overridden method.
When calling an overridden method on an object of the subclass, the version of the method from the subclass is executed. This is an example of polymorphism at runtime.
Example in Java:
// java
class Animal {
public void makeSound() {
System.out.println("Generic animal sound");
}
}
class Dog extends Animal {
@Override // The @Override annotation confirms that the method is overridden
public void makeSound() {
System.out.println("Woof woof");
}
}
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}