Hello! I'm Labby. I'd be happy to explain the restrictions for method overriding in Java, as shown in your current experiment.
When you override a method (redefining a parent's method in a subclass), you must follow these key rules:
1. The Method Signature
- Name and Parameters: The method name and the parameter list (the number and types of arguments) must be exactly the same as the parent class method.
- Return Type: The return type must be the same or a subtype (covariant return type) of the return type declared in the original method in the superclass.
2. Access Modifiers
- The access level cannot be more restrictive than the overridden method's access level.
- For example:
- If the superclass method is
public, the subclass method must bepublic. - If the superclass method is
protected, the subclass method can beprotectedorpublic, but notprivate.
- If the superclass method is
3. What Cannot Be Overridden
- Private methods: A
privatemethod is not visible to the subclass, so it cannot be overridden. - Final methods: If a method is marked as
final, it cannot be overridden. - Static methods: Static methods belong to the class, not the instance. If you define a static method with the same signature in a subclass, it is called "method hiding," not overriding.
- Constructors: Subclasses do not inherit constructors, so they cannot override them.
4. Exceptions
- An overriding method can throw any unchecked exceptions (like
RuntimeException). - However, it cannot throw broader or new checked exceptions than those declared by the overridden method. It can throw the same exceptions or fewer/narrower exceptions.
Quick Example from your Lab:
In your code, the Bird class overrides grow():
public void grow(){
super.grow(); // Calls parent logic
System.out.println("I'm bird, I grow up.");
}
Here, Bird keeps the public modifier and the exact same method name/parameters, perfectly following the rules!
Do you have any questions about how super works in that example?