Inheritance

The Open-Closed Principle says that a system should be open to extension but closed to modification. For example, we can extend the functionality of a class by introducing a subclass:

class ScientificCalculator extends Calculator { ... }

ScientificCalculator inherits the functionality of Calculator. This can save a lot of error-prone code duplication.

Here's the complete code:

TestCalculator.java

Labs

Lab

Look up the formulas for computing compound interest and monthly payments (i.e., to repay a loan). Use this to complete and test the implementation of BusinessCalculator, which extends Calculator.

Lab

We say that ScientificCalculator extends or is a subclass of Calculator. Equivalently, we say that Calculator is a superclass or base class of Calculator.

Polymorphism means that instances of ScientificCalculator can masquerade as instances of Calculator:

Calculator c = new ScientificCalculator();

However, we get into trouble here:

c.sin(); // error

How can c be safely re-typed so that the sin function can be called?

Lab

ScientificCalculator inherits all of the members of Calculator, including those members Calculator inherited from its superclass. Although not explicitly declared, the super class of Calculator is Java's Object class. The Object class provides methods such as toString, hashCode, equals, and getClass. Add code to determine if calc1 and calc2 (declared in TestCalculator.main) are equal. Find out the true class of calc2 (as opposed to its type). How does Java convert calc2 into a string? Why is hashCode needed for all objects?

Lab: Overriding versus Overloading

Overloading means name sharing: several methods can share the same name (provided their parameter lists are different).

Overriding means redefining an inherited method. In this case it's important that the parameter lists are the same.

Overload the sin, cos, and tan methods for ScientificCalculator with versions that simply assign the value computed for an input to the result field:

result = Math.sin(input);

Override the inherited toString method for ScientificCalculator that prints something more user friendly.