Java programs made out of classes.

Classes are used for modeling. 

Define a class define a type. 

User-defined type or reference type. 

A class is a container. 

It contains static members (variables and methods). 

It also contains a blueprint of instance members (variables and methods). 

Instantiate a blueprint with the new operator to get an object. 

Constructors are initialization procedures for objects. 

class Point {
  int x, y; 
  Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
  Point() {
    this(0, 0); 
  }
  public String toString() {
    return "Point at (" + this.x + ", " + this.y + ")"; 
  } 
  public double distanceTo(Point other) {
    int dx = this.x - other.x; 
    int dy = this.y - other.y;
    double distance = Math.sqrt(dx * dx + dy * dy); 
    return distance; 
  } 
}

class Line {
  Point a, b; 
  Line(Point start, Point stop) {
    this.a = start; 
    this.b = stop; 
  }   
  public double length() {
    return a.distanceTo(b); 
  } 
}


Another way:

class Line extends ArrayList<Point> {

}

Not a bad idea but probably overkill. 

class Line extends Point {
  Point target;
  Line(int x, int y, Point target) {
    super(x, y); // constructor chaining 
    this.target = target; 
  } 
}

Class extension mechanism: model in stages. 

Inheritance, polymorphism, constructor chaining. 

The class extension mechanism is the set union of features. 

Horse = { name, talk() }

Unicorn = Horse U { sing() } 

Constructor chaining ensures that when an object 
of a subclass is created the part from the superclass
is created first. 

class Shape {
  int x, y; 
  Shape(int x, int y) {
    this.x = x; 
    this.y = y; 
  } 
}

class Circle extends Shape {
  int radius; 
  Circle (int x, int y, int radius) {
    super(x, y); 
    this.radius = radius; 
  } 
  public double area() {
    return Math.PI * this.radius * this.radius; 
  } 
}


Shape a = new Circle(3, 4, 5); // yes, a circle is a shape

Circle b = new Circle(3, 4, 5); // normal 

Shape c = new Shape(3, 4); // normal 

Circle d = new Shape(3, 4); // not acceptable 

Shape e = new Circle(2, 3, 4); 

e.area(); // not allowed because Shape type has no area

((Circle)e).area(); // by casting 


abstract class Shape {
  ... 
  abstract public double area();
}

class Circle extends Shape {
  ... 
  public double area() {
    ... 
  }
}

Can I use interfaces here? 

interface Shape {
  public double area(); 
}

class Circle implements Shape {
  int x, y, radius;
  Circle(int x, int y, int radius) {
    ... // no super when interface is invlved
  }
  ...
}

We'll see you on Wed. 

Name and date on desk for attendance please. 

--