Question

This is the only question about interfaces in oop I can't seem to fully explain. So again, why in oop can a class implement multiple interfaces?

If you can provide a few examples that would be great. thanks in advance.

Was it helpful?

Solution

Conceptual Example

The way I think about the multiple interfaces is interface is like the verb or adjective, and class is like the subject.

A tiger can run, so the Tiger class may implement Runnable Interface.

A tiger can eat, so the Tiger class may implement Eatable Interface.

Because an instance of the class could have different behaviors, we could have different corresponding interfaces.

Realistic Example

java.util Class HashMap<K,V>

It implements Serializable, Cloneable, Map<K,V>

All of the interfaces are the characteristics of Class HashMap.

OTHER TIPS

First thing is java doesn't support multiple inheritance hence you can not extend two classes at the same time. However, java support implementation of multiple interfaces. The example given by Mingyu seems perfect to me.

interfaces are essentially abstract(ofcourse not by definition, just saying) , therefore all methods have to be implemented in the concrete subclasses, in this way we avoid the deadly diamond of death, supporting multiple inheritance in a way which in itself is the answer for multiple interface implementation to be allowed.

there are many other uses too but due to the above explaination, there isnt any other reason to restrict the concept of multiple implementation....to the best of my knowledge.

Java class cannot extend multiple classes because of diamond ♦ problem. Diamond ♦ problem occurs due of constructor chaining. Constructor is not present in Interface so no diamond ♦ problem will occur if we implement multiple interfaces. That's why Java class can implement multiple interfaces.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top