Introduction: 9.3.0

  • A subclass inherits all public methods from its superclass
    • These methods remain public in the subclass
    • Sometimes we want to modify inherited methods
      • Called overriding methods
  • Overriding an inherited method means providing a method with the same method signature as a method in the superclass
    • method name, parameter type list, return type
    • The method in the subclass will be called instead of the superclass
  • The @Override annotation can be used so the compiler knows you’re trying to override a method
    • This gives you extra checks to make sure you’ve done everything correctly
    • It is generally good practice to do this

Overloading Methods: 9.3.1

  • Overloading a method is when several methods have the same name, but the parameter types, order, or number are different
    • Only method names are identical
    • Allows you to have similar methods which do slightly different things
public class Greeter {
    public String greet() {
        return "Hello!!";
    }
}

public class GreeterEnEspanol {
    @Override
    public String greet() {  // This method is overriding a parent method!
        return "¡Hola!";
    }

    public String greet(String name) {  // This method is overloading greet()!
        return "¡Hola " + name + "!  ¿Como estas?";
    }
}

Inherited Get and Set Methods: 9.3.2

  • To access inherited instance variables (which should be private) the child class should use public accessor and mutator methods to access these

Summary: 9.3.4

  • Method overriding occurs when a public method in a subclass has the same signature as a public method in the superclass
  • All methods must be defined within it’s own class or a superclass
  • A subclass is usually designed to have overridden or additional methods or instance variables
  • A subclass will inherit all public methods from the superclass
    • This includes all setter/getter methods!
    • These remain public in all subclasses
  • Overloading a method is when several methods have the same name, but a different signature
    • Different parameter types, order, or number of parameters