taylorialcom/ ObjectOriented

Inheritance

In the world of Java every child is at least as good as his/her parent, unless it messes something up.

Object oriented languages such as Java provide a mechanism for reusing code known as inheritance.

Object Class

Suppose we have the following class defined:

public class A {

}

Even though the class has no methods explicitly implemented, we can still do the following:

A instance = new A();
System.out.println(instance.toString());

Running this code would produce something like this:

packageName.A@82ba41
public class A {
  public String toString() {
    return "This is an object from the silliest class I have ever seen";
  }
}

Running the code below results in This is an object from the silliest class I have ever seen.

A instance = new A();
System.out.println(instance.toString());

Class Declaration Syntax

public class Shape {
  private Color color;
  private double xCoord;
  private double yCoord;

  public Shape() {
    color = Color.WHITE;
    xCoord = 0.0;
    yCoord = 0.0;
    System.out.println("Shape: constructor");
  }

  public void draw() {
    System.out.println("Shape: draw");
  }

  public void erase() {
    System.out.println("Shape: erase");
  }

  public void move() {
    xCoord += 5.0;
    yCoord += 5.0;
    System.out.println("Shape: move");
  }

  public void zoom(double magnification) {
    System.out.println("Shape: zoom");
  }

  public Color getColor() {
    System.out.println("Shape: getColor");
    return color;
  }

  public void setColor(Color color) {
    this.color = color;
    System.out.println("Shape: setColor");
  }
}
public class Circle extends Shape {
  private double radius;

  public Circle() {
    super();
    radius = 0.0;
    System.out.println("Circle: constructor");
  }

  public void draw() {
    System.out.println("Circle: draw");
  }

  public void erase() {
    super.erase();
    System.out.println("Circle: erase");
  }

  public void zoom(double magnification) {
    radius *= magnification;
    System.out.println("Circle: zoom");
  }

  public void setRadius(double radius) {
    this.radius = radius;
    System.out.println("Circle: setRadius");
  }

  public double getRadius() {
    System.out.println("Circle: getRadius");
    return radius;
  }
}

Can you figure out what the following program will display?

public static void main(String[] args) {
  Shape shape = new Shape();
  Circle circle = new Circle();
  shape.move();
  circle.move();
  shape.draw();
  circle.draw();
  shape.zoom();
  circle.zoom();
  shape.erase();
  circle.erase();
  circle.getRadius();
}

Note:

The is-a Lingo

Visibility Modifiers