Overriding Methods
Part of: Inheritance
Replacing Inherited Behavior. Sometimes a subclass needs to do a job differently than its superclass. Method overriding lets a subclass provide its own version of a method that already exists in the superclass. The method keeps the same name, parameters, and return type , but supplies a new body. How Overriding Works. Now new Dog().speak() returns "woof", while new Animal().speak() returns "some sound". The subclass version replaces the inherited one for Dog objects. The @Override Annotation. Writing @Override above the method is optional but strongly recommended. It tells the compiler "I intend to override." If you misspell the name or get the parameters wrong, the compiler reports an error instead of silently creating a brand-new method. Override vs. Overload. Do not confuse these: - Overriding : same signature, in a subclass , replaces inherited behavior. - Overloading : same name but different parameters , usually in the same class. Signature Rules. To legally override: - The method name and parameter list must match exactly. - The return type must match (or be a subtype). - You cannot make the access more restrictive (e.g., public cannot become private). What usually goes wron
Challenge: Override describe()