Java Reference
In-Depth Information
13. System.out.println(“Drawing a Picture”);
14. }
15.
16. public Rectangle getDimensions() {
17. return dimensions;
18. }
19.
20. public String getArtist() {
21. return artist;
22. }
23.
24. public void resize(int width, int height) {
25. if(width < Drawable.MAX_WIDTH) {
26. dimensions = new Rectangle(width, height);
27. }
28. }
29. }
Because Picture is not declared asbstract , Picture must implement all the methods of
Drawable for it to compile, which it does. Notice the Picture class can have any number of
fi elds and methods in addition to the methods of Drawable . But one thing is certain: if you
have an instance of Picture , then you can invoke draw , resize , and getDimensions on it
because Picture implements Drawable .
What Is the Purpose of Interfaces?
An interface can contain abstract method declarations but no method implementations.
Why would we create such an entity? Well, one of the main uses of interfaces is to
provide a communication contract between two objects. In other words, two objects that
need to “interface” with each other use an interface. If you know a class implements an
interface, then you know that class contains concrete implementations of the methods
in that interface, and you are guaranteed to be able to invoke those methods safely and
know the object has implemented them.
For example, the java.lang.Runnable interface contains a single method:
public void run();
If you give me an object whose class implements Runnable , then I can invoke run(); on that
object, even though I might not know or care about any other methods and fi elds of the object.
This is a very powerful feature of the Java language used throughout the Java API, and
any well-designed application will use interfaces extensively.
Search WWH ::




Custom Search