Java Reference
In-Depth Information
Let's look at an example. Suppose we have the following interface named Drawable :
1. import java.awt.Rectangle;
2.
3. public interface Drawable {
4. int MAX_WIDTH = 1024;
5.
6. public void draw();
7. abstract Rectangle getDimensions();
8. void resize(int w, int h);
9. }
The Drawable interface declares one fi eld, MAX_WIDTH , and three methods. Note that MAX_
WIDTH is public , static , and final , even though these specifi ers were omitted. Similarly,
the draw method is abstract , the getDimensions method is public , and the resize method
is both public and abstract .
Implementing Interfaces
A class implements an interface using the implements keyword in the declaration of the
class. A class can implement multiple interfaces by separating the interface names with
commas. For example,
public class Picture implements Drawable
public class Flower implements Plant, Drawable
A class that implements an interface must do one of the following:
Override all the methods of the interface.
Declare itself as abstract.
Let's look at an example. The following Picture class implements the Drawable
interface. Study the code and determine if it compiles successfully.
1. import java.awt.Rectangle;
2.
3. public class Picture implements Drawable {
4. private Rectangle dimensions;
5. private String artist;
6.
7. public Picture(String artist, int width, int height) {
8. this.artist = artist;
9. dimensions = new Rectangle(width, height);
10. }
11.
12. public void draw() {
Search WWH ::




Custom Search