CS115 Class Exercise on Interfaces NAME______________________
Shape Example from textbook:
// Represents circle shapes.
public class Circle implements Shape {
private double radius;
// Constructs a new circle with the given radius.
public Circle(double radius) {
this.radius = radius;
}
// Returns the area of this circle.
public double getArea() {
return Math.PI * radius * radius;
}
// Returns the perimeter of this circle.
public double getPerimeter() {
return 2.0 * Math.PI * radius;
}
}
// Represents rectangle shapes.
public class Rectangle implements Shape {
private double width;
private double height;
// Constructs a new rectangle with the given dimensions.
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
// Returns the area of this rectangle.
public double getArea() {
return width * height;
}
// Returns the perimeter of this rectangle.
public double getPerimeter() {
return 2.0 * (width + height);
}
}
// A general interface for shape classes.
public interface Shape {
public double getArea();
public double getPerimeter();
}
Alternative setup: no “public” on methods (they must be public)
public interface Shape {
double getArea();
double getPerimeter();
}
We can compress this down to
API for Circle, which implements Shape:
Circle(double radius)
double getArea()
double getPerimeter()
API for Rectangle, which implements Shape:
Rectangle(double width, double height)
double getArea()
double getPerimeter()
API for Shape:
double getArea()
double getPerimeter()
1. Create a Circle object named “apple” of radius 10. Note that this involves setting up a Circle variable named “apple” that references a Circle object.
Circle _______ = new Circle( ____ );
2. Create a Rectangle object named “box”
3. Create a Shape variable named “shape1” that references the Circle named “apple”
Shape _________ = __________
Note that after this executes, the Circle object has two references to it, so two names, “apple” and “shape1”.
4. Create a Shape variable “shape2” that references the Rectangle named “box”
5. Create a Shape array named shapeHolder holding 3 Shapes, and put the “apple” object in spot 0, the “box” object in spot 1, and null in spot 2.
Shape[] _____________ = new Shape[ ___ ];
6. Write a line of code to print out the area of the very first shape in shapeHolder, using the array name, access to the 0’th element, and the method that gets the area.