L07 - Shapes Lab
In this lab, we'll work with Abstract Classes.
- Start VS Code.
- During the lecture we discussed the following classes:
Shape– an abstract classCircle– a class that is derived from ShapeEllipse– a class that is also derived from Shape
- Using the
Circleclass a guide and the Ellipse slide, finish writing theEllipseclass - Using the
Circleclass as a guide, write a class calledRectangle:- extend the
Shapeclass - define member variables of type
doublefor thewidthandheight - create one or more constructors, as appropriate
- override the
equals,toString,findArea, andfindPerimetermethods
- extend the
- Create a new class with the name
ShapeTest. - This is the body of the class
ShapeTest:
public class ShapeTest {
public static void main(String[] args) {
Shape[] myShapes = new Shape[10];
Circle myCircle = new Circle(10.0);
double expected = 314.16;
System.out.println("Circle Area: " + myCircle.findArea());
myShapes[0] = new Circle(10.0);
expected = 314.16;
System.out.println("Circle in Shapes Array Area: " + myShapes[0].findArea());
myShapes[1] = new Ellipse(5.0, 10.0);
expected = 157.08;
System.out.println("Ellipse in Shapes Array Area: " + myShapes[1].findArea());
myShapes[2] = new Rectangle(5.0, 10.0);
expected = 50.0;
System.out.println("Rectangle in Shapes Array Area: " + myShapes[2].findArea());
}
}
When you run the tests, notice that Java knows what particular kind of object (Circle, Rectangle, or Ellipse) has been stored in the array of Shapes.
No Comments