Why do we NEED interfaces? Well we probably don't NEED them but they do come in ever so helpful.
At a very basic level they allow us to specify a features of a class. For example if a class implements Comparable than I know that it has the compareTo() method. I also know that this object is compatible with various methods that use the compareTo() method. For example if I make a List that is Comparable then I can use Collections.sort() to sort my list.
They also allow for abstraction. I may want to implement an algorithm that searches a string for a particular word. Now I COULD just have the argument be a String -- but since strings are an immutable class they are not always the best place to store textual data (especially while it is being processed) so if I step back and make take an argument of CharSequence then I now know that I can pass in Strings or CharBuffer, or StringBuffer -- So my method is now more abstract and more useful.
Interfaces let us decouple the implementation from the interface. This has solved a great number of problems dealing with versions. Allowing newer code to plugin to older code without having to recompile the whole project.
In Java you can only have one parent class -- but you can implement many interfaces. That means that I can create a class that is Compareable, Serializable, CharSequence, DataInput, And DataOutput. Meaning that I created a string that can be both written to (DataOutput) and read From (DataInput), I can make comparisons and I can serialize it (for persistance or to transmit over a communications channel). I can do all of this and have still derive the class from any base class I want.
Interfaces allow me to abstract objects so that I can have a collection of say Animals without careing what kind of Animals are in the collection.
Interfaces for the key to many design patterns.
Interfaces are key to most application frameworks.
Interfaces increase abstraction allowing us to make more and more generalized designs (and thus fancy application frameworks).
Kacee Saxena wrote:Although i dont think it is a good practice to declare an interface, and never implement it , and directly access its state variables.
Paul Clapham wrote:
You also seem to have a question about whether it's a good idea to declare an enum inside an interface. That's a completely separate question. As you've seen, the language permits it. The language also permits declaring an enum on its own, not inside any class or interface. Both are legitimate things to do. However declaring an enum inside an interface doesn't require any class to ever implement that interface -- if that was a question you had. Declaring an interface likewise doesn't require any class to ever implement the interface, although it's rather pointless to write an interface which isn't going to be implemented. That's true whether or not it contains an enum.
OCA7
Don't get me started about those stupid light bulbs. |