Subtyping in Java

Examples illustrate Java subtyping.



public class Shape {
	protected double width; // the width of the bounding box
	protected double height;  // the height of the bounding box
	
	public Shape(double w, double h) {
		width = w;
		height = h;
	}
	
	public double size() {
		return width * height;
	}
	
	public Shape copy() {
		System.out.println("Shape copy");
		return new Shape(width, height);
	}
	
	public Shape combine(Shape s) {
		System.out.println("Shape combine");
		return new Shape(width + s.width, height + s.height);
	}

}


public class Square extends Shape{
	
	public Square(double side) {
		super(side, side);
	}
	
	public Square copy() {
		System.out.println("Square copy");
		return new Square(width);
	}
	
	public Square combine(Square s) {
		System.out.println("Square combine");
		return new Square(width + s.width);
	}

}


public class Circle extends Shape {
	public Circle(double side) {
		super(side, side);
	}
	
	public Circle copy() {
		System.out.println("Circle copy");
		return new Circle(width);
	}
	
	public Circle combine(Circle s) {
		System.out.println("Circle combine");
		return new Circle(width + s.width);
	}
}


public class SubtypingTest {

	public static void main(String[] args) {
		Shape s1 = new Shape(5,10);
		Shape s2 = new Square(3);
		Square sq1 = new Square(5);
		Circle c1 = new Circle(7);
		
		System.out.println(s1.copy().size());
		System.out.println(s2.copy().size());
		
		s1.combine(s2);
		s2.combine(s1);
		sq1.combine(s1);
		sq1.combine(sq1);
		c1.combine(s1);
		c1.combine(sq1);
	}

}


CSci 4651 course.