Java Reference
In-Depth Information
If a class implements multiple interfaces, then an implementing class must override the
methods of all the interfaces it implements. Suppose we have the following interface named Plant :
1. public interface Plant {
2. public void photosynthesize();
3. }
The following Flower plant successfully implements both Plant and Drawable :
1. import java.awt.Rectangle;
2.
3. public class Flower implements Plant, Drawable {
4. public int numOfLeaves;
5.
6. public void photosynthesize() {
7. System.out.println(“Plant is photosynthesizing”);
8. }
9.
10. public void draw() {
11. System.out.println(“Drawing a Plant”);
12. }
13.
14. public Rectangle getDimensions() {
15. return new Rectangle(0,0);
16. }
17.
18. public void resize(int w, int h) {
19. System.out.println(“Resizing a Plant?”);
20. }
21. }
I can understand drawing a fl ower, but resizing a fl ower probably doesn't make any
sense. There are defi nitely situations in Java where I have implemented an interface and
have been forced to write methods that I did not want to implement. It is not unusual to
have empty method bodies in these situations, which might apply here to the resize and
getDimension methods of Flower .
Interfaces and Data Types
If a class implements an interface, objects from that class are also the data type of the
interface. For example, the Picture and Flower classes, which seem like two totally
unrelated classes, actually share a common data type because both classes implement
Drawable . Objects of type Picture and Flower are also objects of type Drawable . An
object taking on the form of different data types is referred to as polymorphism, and we
discuss the effects of interfaces on polymorphism in detail in Chapter 6.
Search WWH ::




Custom Search