1. Interface!! Why?
A bit of history never hurt anyone.
The Java platform and language
began as an internal project at
Sun Microsystems in December
1990, providing an alternative to
the C++/C programming languages.
Engineer Patrick Naughton had
become increasingly frustrated with
the state of Sun's C++ and C APIs
(application programming interfaces)
and tools.[wikipedia]
2. This was one of his problems
Deadly Diamond of Death
Class B and class C both inherit
from class A and both
override the print() method .
Both inherit the “i” instance
variable .
Imagine that the “i” instance
variable is used by both B and
C ,with different values . What
happens if the D needs both
values of “i”?
Problem with the multiple
inheritance. Which print()
method runs when you call
print() in class D.
3. Interface to the rescue!
A Java interface is pure abstract Java gives us a solution . An
class. Interface. A Java interface solves
the problem by giving the
polymorphic benefits of the
multiple inheritance avoiding
Deadly Diamond of Death.
interface Pet Java does that by making all the
methods abstract.That way the
subclass must implement the
methods ,so the JVM knows which
abstract void beFriendly(); two inherited version it needs to
call.
abstract void play(); Interface shows a “has-a”
relationship among classes.
4. The boring coding stuff
To DEFINE an interface:
public interface Pet{
abstract void beFriendly();
abstract void play(); }
To IMPLEMENT an interface:
public class dog extends Canine implements Pet{
void beFriendly(){….}
void play(){….}
}
6. Reference materials
These are the places from where I used my
copy paste skills :
1. www.wikipedia.org
2. Head First Java - Kathy Sierra and Bert Bates .
(2nd edition, pages 244-247)