Answer on Question#54253, Programming / Java | JSP | JSF
TESTShape.java
public class TestShape {
public static void main(String[] args) {
// Rectangle test
double width = 5.00, length = 7.00;
Shape rectangle = new Rectangle(width, length);
System.out.print("\nRectangle width %.2f %.2f: ",width,length);
System.out.print("\nResulting area: %.2f: ", rectangle.area());
// Square test
double side = 5.00;
Shape square = new Square(side);
System.out.print("\nSquare side %.2f: ", side);
System.out.print("\nResulting area: %.2f: ", square.area());
// Circle test
double radius = 5.00;
Shape circle = new Circle(radius);
System.out.print("\nCircle radius: %.2f ", radius);
System.out.print("\nResulting Area: %.2f ", circle.area());
// Triangle test
double base = 5.00, height = 4.00;
Shape triangle = new Triangle(base,height);
System.out.print("\nTriangle base and height %.2f %.2f: ",base,height);
System.out.print("\nResulting area: %.2f: ", triangle.area());
}
}Square.java
public abstract class Shape {
public abstract double area();
}Square.java
public class Square extends Shape {
private final double side; //sides
public Square() {
this(1);
}
public Square(double side) {
this.side = side;
}
@Override
public double area() {
// A = l * l
return side*side;
}
}Circle.java
public class Circle extends Shape {
private final double radius;
final double pi = Math.PI;
public Circle() {
this(1);
}
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return pi * Math.pow(radius, 2);
}
}//////////////////////
Triangle.java
public class Triangle extends Shape {
private final double base, height;
public Triangle() {
this(1,1);
}
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double area() {
double s = 0.5*base*height;
return s;
}
}////////////////////
Rectangle.java
public class Rectangle extends Shape {
private final double width, length; //sides
public Rectangle() {
this(1,1);
}
public Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
@Override
public double area() {
// A = w * l
return width * length;
}
}////////////////////
/////////////////////