I would like to add something to the previous answer.
As you understood from the deep explanation given by Tilsan The Fighter multiple inheritance is not supported by Java.
Alternatively you should use one of delegation design patterns. I know that sometimes the code looks more verbose than code done using multiple inheritance but this is the price we have to pay.
You asked a question why do you need to create class that implements more than one interface? I'd ask you a question why do you need interface at all? I think that the answer is that this allows you to separate interface (contract) from concrete implementation, make modules independent, simplify re-factoring and make programs more flexible: you can switch implementations only if the concrete implementation is hidden by interface.
If your class can be used in different contexts as A and as B (where A and B are interfaces) the class should implement 2 interfaces.
Example: Let's assume that you have a business interface Foo that declares only one method
int foo(String str);
Now you create a couple of classes A and B that implement Foo:
public class A implements Foo {
public int foo(String s) {
return s.length();
}
}
public class B implements Foo {
public int foo(String s) {
return s.hashCode();
}
}
Now you would like to create collection of Foo:
Collection<Foo> collection = new ArrayList<Foo>();
collection.add(new A());
collection.add(new B());
Code that uses this collection does not know anything about the concrete implementation but it does not bother it to invoke foo().
Now you wish to sort this collection. One of the ways is to implement yet another interface Comparable:
public class A implements Foo, Comparable<Foo> {
public int foo(String s) {
return s.length();
}
public int compareTo(Foo o) {
return getClass().getName().compareTo(o.getClass().getName());
}
}
Once you are done you can say:
Collections.sort(collection);
And the collection will be sorted according to the rule defined in compareTo().
Now you probably wish to serialize the instances of A and B. To do this you have to implement yet another interface Serializable. Fortunately Serializable is a special interface that does not declare any method. JVM knows to serialize and desirialize objects that are instances of Serializable.
public class A implements Foo, Comparable<Foo>, Serializable {
public int foo(String s) {
return s.length();
}
public int compareTo(Foo o) {
return getClass().getName().compareTo(o.getClass().getName());
}
}
Class B looks the same.
Now we can say:
DataOutputStream os = new DataOutputStream(new FileOutputStream("/tmp/foo.dat"));
os.writeObject(new A());
os.writeObject(new B());
os.flush();
os.close();
and store our objects in file /tmp/foo.dat
. We can read the objects later.
I tried to show why do we need classes that implement several interfaces: each interface gives the class its behavior. Comparable allows sorting collection of such instances. Serializable allows serialization etc.