Test Shape, Rectangle, Circle, and the ShapeUtil Class - Java Object Oriented Design

Java examples for Object Oriented Design:Inheritance

Description

Test Shape, Rectangle, Circle, and the ShapeUtil Class

Demo Code

abstract class Shape {
  private String name;

  public Shape() {
    this.name = "Unknown shape";
  }/*from ww  w  .  j a va 2s  . c o  m*/

  public Shape(String name) {
    this.name = name;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  // Abstract methods
  public abstract void draw();

  public abstract double getArea();

  public abstract double getPerimeter();
}

class Rectangle extends Shape {
  private double width;
  private double height;

  public Rectangle(double width, double height) {
    // Set the shape name as "Rectangle"
    super("Rectangle");
    this.width = width;
    this.height = height;
  }

  // Provide an implementation for inherited abstract draw() method
  public void draw() {
    System.out.println("Drawing a rectangle...");
  }

  // Provide an implementation for inherited abstract getArea() method
  public double getArea() {
    return width * height;
  }

  // Provide an implementation for inherited abstract getPerimeter() method
  public double getPerimeter() {
    return 2.0 * (width + height);
  }
}

class Circle extends Shape {
  private double radius;

  public Circle(double radius) {
    super("Circle");
    this.radius = radius;
  }

  // Provide an implementation for inherited abstract draw() method
  public void draw() {
    System.out.println("Drawing a circle...");
  }

  // Provide an implementation for inherited abstract getArea() method
  public double getArea() {
    return Math.PI * radius * radius;
  }

  // Provide an implementation for inherited abstract getPerimeter() method
  public double getPerimeter() {
    return 2.0 * Math.PI * radius;
  }
}

class ShapeUtil {
  public static void drawShapes(Shape[] list) {
    for (int i = 0; i < list.length; i++) {
      list[i].draw(); // Late binding
    }
  }

  public static void printShapeDetails(Shape[] list) {
    for (int i = 0; i < list.length; i++) {
      String name = list[i].getName(); // Late Binding
      double area = list[i].getArea(); // Late binding
      double perimeter = list[i].getPerimeter(); // Late binding

      System.out.println("Name: " + name);
      System.out.println("Area: " + area);
      System.out.println("Perimeter: " + perimeter);
    }
  }
}

public class Main {
  public static void main(String[] args) {
    // Create some shapes, draw, and print their details
    Shape[] shapeList = new Shape[2];
    shapeList[0] = new Rectangle(2.0, 4.0); // Upcasting
    shapeList[1] = new Circle(5.0); // Upcasting

    // Draw all shapes
    ShapeUtil.drawShapes(shapeList);

    // Print details of all shapes
    ShapeUtil.printShapeDetails(shapeList);
  }
}

Result


Related Tutorials