In Java, can an interface extend several interfaces?

In Java, can an interface extend several interfaces? This code looks to be valid in my IDE and compiles:

interface Foo extends Runnable, Set, Comparator<String> { }

However, I looked up on the internet from various sources that multiple inheritances were not permitted in Java as said in this blog from orcale and scaler topics. Why does it look that interfaces are an exception?

Yes an interface can extend several interfaces, because it’s not a class but a type.

The multiple inheritance is indeed not allowed, because it creates conflict with (possible) duplicate variable names. Oracle explains it at their learning module:

One significant difference between classes and interfaces is that classes can have fields whereas interfaces cannot. In addition, you can instantiate a class to create an object, which you cannot do with interfaces. […] One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes. For example, suppose that you are able to define a new class that extends multiple classes. When you create an object by instantiating that class, that object will inherit fields from all of the class’s superclasses. What if methods or constructors from different superclasses instantiate the same field? Which method or constructor will take precedence? Because interfaces do not contain fields, you do not have to worry about problems that result from multiple inheritance of state.

3 Likes