Interfaces, what the advantages ?
We can feel the advantages of class inheritance from at lease sharing
and reusing the super class's methods. But in an interface, there are
only abstract methods, and we have implement all the methods in the
class that implements this interface, why do we still use interface?
Why don't we define the methods and write their code directly in the
class without implementing any interface or something like that? In
other words, what are the advantages of using interface? I have read
some books, in which the authors just say it's a protocol and so on. I
still can not understand the necessity of using interface. Can anybody
give me a sample to illustrate this? Thanks.
Re: Interfaces, what the advantages ?
Another source: What Is an Interface? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Concepts)
Using interfaces allows a class to have more than one data type.
Because of java's strict datatyping, having more than one type for a class allows one class to be used as an argument to many different methods that each take a different datatype. A common usage is as listeners for the mouse and keyboard events.
Re: Interfaces, what the advantages ?
Suppose a program P(I) exists that depends on an interface I. Also suppose that you and I both implement that interface I, i.e. Iimpl1 and Iimpl2. That program P doesn't care less what the implementation is, it runs equally fine with either implementation, i.e both P(Iimpl1) and P(Iimpl2) are valid programs without having to rewrite one single line in program P(I). Try to do that without interfaces.
kind regards,
Jos