This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Could someone help explain a practical use of interfaces. I understand from reading "Head First Java" that they allow a program to implement methods from other inheritance trees. I also use subclasses and abstract classes in many programs, they are very useful. However, if there is no code in a method of an interface, how am I buying any additional functionality by implementing that interface? The bonus of inheritance is that the code is put in a single place and it can be used by classes that need it. How does it help if no actual code is in that class? A class (interface) without code can only act as an abstraction level, right? Can I get an example to help me understand how interfaces allow me to implement a useful function?
Hi Tyler, Interfaces are very useful because we can achieve the polymorphism effect by using them. If you don't have the idea of polymorphism then try to explore that first.
Joined: Nov 17, 2003
I do understand polymorphism and I create classes that use inheritance. I've used abstract classes and have exentended them to subclasses I have created, but I haven't yet seen a useful interface example. I'm sure they are very useful and thats why I want to understand, but I haven't seen why yet. Interfaces I have seen so far provide no functionality to my classes. How do they provide functionality?
Interfaces I have seen so far provide no functionality to my classes. How do they provide functionality? They don't. All they do is to make a statement about what messages can be send to objects of a class that implements that interface. Here's a example:
Why do you want that? Well, it allows you to write code that talks to all objects of classes that implemet Stringable, without knowing what specific type you're dealing with.
This code works even with objects of classes that are implemented _after_ do() itself. Also, if you would do this with abstract classes, what kind of implementation of toString() do you want to put in it? You just don't know anything about the derived classes, and you don't have to with interfaces. Let me suggest a book that provides more detailed explanations and comes for free, it is called Thinking in Java. HTH, Tobias [ April 16, 2004: Message edited by: Tobias Hess ] [ April 16, 2004: Message edited by: Tobias Hess ]