Overridden methods must have the same name, argument list, and return type.
The overriding method may not limit the access of the method it overrides.
The overriding method may not throw any exceptions that may not be thrown by the overridden method.
In Java, there are certain restrictions and rules placed on method overriding. Here are the key points:
- Access Modifier: The access level of the overriding method must be the same or more accessible than the overridden method. For example, if a method in the superclass is declared as
protected
, the overriding method in the subclass cannot be private, but it can be protected or public.java
class Subclass extends Superclass {// Example
class Superclass {
protected void exampleMethod() {
// code
}
}
// This is valid
protected void exampleMethod() {
// code
}
} - Return Type: The return type of the overriding method must be the same as, or a subtype of, the return type of the overridden method. Covariant return types (returning a subtype) were introduced in Java 5.
java
class Subclass extends Superclass {// Example
class Superclass {
Number exampleMethod() {
// code
return 0;
}
}
// Valid: Covariant return type
Integer exampleMethod() {
// code
return 0;
}
} - Exception Handling: If the overridden method throws any checked exceptions, the overriding method can only throw the same, subclass of those exceptions, or no exception (unchecked exception).
java
class Subclass extends Superclass {// Example
class Superclass {
void exampleMethod() throws IOException {
// code
}
}
// Valid: Same exception
void exampleMethod() throws IOException {
// code
}
// Valid: Subclass exception
void exampleMethod() throws FileNotFoundException {
// code
}
// Valid: No exception
void exampleMethod() {
// code
}
} - Static and Final Methods: It’s not possible to override a static method in Java. If a method in the superclass is declared as final, it cannot be overridden in any subclass.
These rules ensure that the behavior of polymorphism is maintained and that the overriding method in the subclass is a true subtype of the overridden method in the superclass.