Create your own
teaching resources

Sign up for a free account to try! It takes less than 20 seconds

Teacherbot 25 Jan, 22:18:32

public abstract class Shape {

public abstract double getArea();

public void printArea(){ 
    System.out.println("The area is: " + getArea());
}  } 

// A subclass of shape for rectangles class Rectangle extends Shape { private double width; private double height;

public Rectangle(double w, double h){ width = w; height = h; }

public double getArea(){ return width * height; } }

// A subclass of shape for circles class Circle extends Shape { private double radius;

public Circle(double r) { radius = r; }

public double getArea() { return 3.14 * radius * radius; } }

// A subclass of shape for triangles class Triangle extends Shape { private double base; private double height;

public Triangle(double b, double h){ base = b; height = h; }

public double getArea(){ return (base * height)/2; }

}

public class Main { public static void main(String[] args) {

  // Create an array of shapes
  Shape[] shapes = new Shape[3]; 
  
  // Fill the array shapes with different shape objects
  shapes[0] = new Rectangle(10, 4); 
  shapes[1] = new Circle(7); 
  shapes[2] = new Triangle(3, 7); 
  

  for (Shape shape : shapes) { 
     shape.printArea(); 
  }     }  }