Inheritance Hullabaloo

Inheritance lets us define classes as extensions of other classes. It lets us:

  1. reduces code duplication
  2. encourages code reuse
  3. simplifies our code
  4. simplifies maintenance and extending our code (open-closed!). • Remember: variables can refer to subtype objects! • Subtypes can be used wherever Supertype objects are expected (substitution).

<aside> ⚙️ Method lookup algorithm ⚙

  1. A variable and its data type are accessed
  2. The object whose address is bound to the variable is retrieved
  3. The type of the object is retrieved and must have an IS-A relationship with the variable data type
  4. The class of the runtime object is searched for a method match
  5. If no match is found, the superclass is searched for a method match
  6. This is repeated until a match is found, or the class hierarchy is exhausted (all the way up to Object) and the program crashes
  7. Methods that override always take precedence. </aside>

QUIZ: Create class, create toString() but don’t override it, call on it and see the result.

the default implementation of toString() which is inherited by every class that extends Object, i.e., every class that doesn’t extend anything else. It looks like a combination of the class name and a unique ID, doesn’t it

// In other words if we print an object without overriding the toString() method then we get a useless hodge podge of letters and numbers.

// A zero parameter constructor (constructor with no parameters) is not the same as a default constructor (we don’t write one at all, Java fills in one with a default values to the super constructor) are not the same

Protected Access

The closer the inheritance relationship is supported by the protected access.

Stronger than public but not Fully private.

protected classes can be accessed by subclasses (children) of the same package.