Develop the ‘Shape’ application such that: ‘Rectangle’, ‘Ellipse’, and ‘Triangle
ID: 3818823 • Letter: D
Question
Develop the ‘Shape’ application such that:
‘Rectangle’, ‘Ellipse’, and ‘Triangle’ classes inherit from the ‘Shape’ class.
Develop the ‘Square’ and ‘Circle’ class where ‘Square’ inherits from ‘Rectangle’ and ‘Circle’ inherits from ‘Ellipse’. ‘Triangle’ has no derived class. For each class, implement the overridden methods ‘draw’, ‘move’, and ‘erase’. Each method should only have an output statement such as “Rectangle – draw method” that will be displayed when the method is invoked.
Implement the default constructors for each class with a corresponding message to be displayed when invoked. No initializations are required; that is, the output message will be the only executable statement in the constructors.
Do not implement any other methods for these classes ( i.e., ‘toString’, ‘equals’, getters and setters ).
Implement a ‘ShapeTest’ class which will instantiate an object of each class.
Exercise each of the ‘draw’, ‘move’, and ‘erase’ methods of each class
Remember to make sure that there is only a single class per file.
Explanation / Answer
public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}
public class Triangle extends Shape {
private final double a, b, c;
public Triangle() {
this(2,2,2);
}
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double area() {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
public double perimeter() {
return a + b + c;
}
}
public class Circle extends Shape
{
private double radius;
double pi = Math.PI;
public Circle() {
this(1);
}
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return pi * Math.pow(radius, 2);
}
public double perimeter() {
return 2 * pi * radius;
}
}
public class TestShape {
public static void main(String[] args) {
double a = 5, b = 3, c = 4;
Shape triangle = new Triangle(a,b,c);
System.out.println("Triangle sides are: " + a + ", " + b + ", " + c+ " Resulting Area: " + triangle.area()+ " Resulting Perimeter: " + triangle.perimeter() + " ");
double radius = 5;
Shape circle = new Circle(radius);
System.out.println("Circle radius: " + radius+ " Resulting Area: " + circle.area()+ " Resulting Perimeter: " + circle.perimeter() + " ");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.