Java Reference
In-Depth Information
The following is the complete code for our Shape interface. It declares that shapes
have methods to compute their areas and perimeters as type double :
1 // A general interface for shape classes.
2 public interface Shape {
3 public double getArea();
4 public double getPerimeter();
5 }
The methods of an interface are sometimes called abstract methods because we
only declare their names and signatures; we don't specify how they will be imple-
mented.
Abstract Method
A method that is declared (as in an interface) but not implemented.
Abstract methods represent the behavior that a class promises to implement
when it implements an interface.
Writing the public keyword on an interface's method headers is optional. We
chose to include the public keyword so that the declarations in the interface would
match the headers of the method implementations in the classes. The general syntax
we'll use for declaring an interface is the following:
public interface <name> {
public <type> <name>(<type> <name>, ..., <type> <name>);
public <type> <name>(<type> <name>, ..., <type> <name>);
...
public <type> <name>(<type> <name>, ..., <type> <name>);
}
Although superficially, classes and interfaces look alike, an interface cannot be
instantiated; that is, you cannot create objects of its type. In our case, any code trying
to create a new Shape() would not compile. It is, however, legal to declare variables
of type Shape that can refer to any object that implements the Shape interface, as
we'll explore in a moment.
Implementing an Interface
Now that we've written a Shape interface, we want to connect the various classes of
shapes to it. To connect a class to our interface with an is-a relationship, we must do
two things:
1. Declare that the class “implements” the interface.
2. Implement each of the interface's methods in the class.
 
Search WWH ::




Custom Search