Java Reference
In-Depth Information
The general syntax for declaring that a class implements an interface is the following:
public class <name> implements <interface> {
...
}
We must modify the headers of our various shape classes to indicate that they
implement all of the methods in the Shape interface. The file Rectangle.java , for
example, should begin like this:
public class Rectangle implements Shape {
...
}
When we claim that our Rectangle class implements Shape , we are promising
that the Rectangle class will contain implementations of the getArea and
getPerimeter methods. If a class claims to implement Shape but does not have a
suitable getArea or getPerimeter method, it will not compile. For example, if we
leave the body of our Rectangle class empty and try to compile it, the compiler will
give errors like the following:
Rectangle.java:2: Rectangle is not abstract and does not override abstract
method getPerimeter()
public class Rectangle implements Shape {
1 error
In order for the code to compile, we must implement the getArea and
getPerimeter methods in our Rectangle class. We'll define a Rectangle object
by a width and a height. Since the area of a rectangle is equal to its width times its
height, we'll implement the getArea method by multiplying its fields. We'll then use
the perimeter formula 2 * (w + h) to implement getPerimeter . Here is the com-
plete Rectangle class that implements the Shape interface:
1 // Represents rectangular shapes.
2 public class Rectangle implements Shape {
3
private double width;
4
private double height;
5
6 // constructs a new rectangle with the given dimensions
7
public Rectangle( double width, double height) {
8
this .width = width;
9
this .height = height;
10 }
 
Search WWH ::




Custom Search