Creating Subclasses

Java notation:

class Shape { ... }
class Rectangle extends Shape { ... }
class Ellipse extends Shape { ... }
class FillRectangle extends Rectangle { ... }

UML notation:

A is a subclass of B (or B is a super class of A) if:

A is B
A extends B
A extends a subclass of B

Notation:

A <: B

For example:

FillRectangle <: Rectangle <: Shape <: Object

Of course we also can write:

FillRect <: Object

Inheritance Rule:

if A <: B, then A inherits the members of B

Example: Extending Calculator

Assume:

public class Calculator {
   protected double result = 0;
   public void add(double input) {
      result = result + input;
   }
   public void mult(double input) {
      result = result * input;
   }
   public void sub(double input) {
      result = result - input;
   }
   public void div(double input) {
      result = result / input;
   }
   public void setResult(double init) {
      result = init;
   }
   public double getResult() {
      return result;
   }
   public void clear() {
      result = 0;
   }
}

The extension:

public class ScientificCalculator extends Calculator {
   public void sin() {
      result = Math.sin(result);
   }
   public void cos() {
      result = Math.cos(result);
   }
   public void exp() {
      result = Math.exp(result);
   }
}

Usage:

public class TestScientificCalculator {
   public static void main(String[] args) {
      ScientificCalculator calc = new ScientificCalculator();
      calc.setResult(Math.PI);
      calc.cos();             
      calc.add(10);           
      System.out.println("result = " + calc.getResult());
      System.out.println("expected: 9.0");
   }
}

Example: Extending JComponent

A class can also redefine or override a method inherited from a super class. For example, in Java's Swing package windows and their contents are all instances of the JComponent class. Each is provided with a paintComponent method that the OS calls if the window needs to be redrawn. (For example, after a resize.) Typically, we override this method in JComponent subclasses if we want custom graphics to appear in the component.

The extension:

class ChartComponent extends JComponent {

   public void paintComponent(Graphics gc) {
      super.paintComponent(gc); // call inherited version
      gc.setColor(Color.RED);
      gc.fillRect(0, 0, 100, 10);
      gc.setColor(Color.BLUE);
      gc.fillRect(0, 10, 150, 10);
      gc.setColor(Color.GREEN);
      gc.fillRect(0, 20, 75, 10);
      gc.setColor(Color.YELLOW);
      gc.fillRect(0, 30, 200, 10);
   }
}

Usage:

public class ChartViewer {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setSize(300, 400);
      frame.setTitle("Frame Viewer");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      ChartComponent component = new ChartComponent();
      frame.add(component);
      frame.setVisible(true);
   }
}

Output: