问题
I know that multiple inheritances between Interfaces is possible, e.g.:
public interface C extends A,B {...} //Where A, B and C are Interfaces
But is it possible to have a regular Class inherit from multiple Interfaces like this:
public class A implements C,D {...} //Where A is a Class and C and D are interfaces
回答1:
A Java class can only extend one parent class. Multiple inheritance (extends) is not allowed. Interfaces are not classes, however, and a class can implement more than one interface.
The parent interfaces are declared in a comma-separated list, after the implements keyword.
In conclusion, yes, it is possible to do:
public class A implements C,D {...}
回答2:
public class A implements C,D {...} valid
this is the way to implement multiple inheritence in java
回答3:
In a word - yes.
Actually, many classes in the JDK implement multiple interfaces. E.g., ArrayList implements List, RandomAccess, Cloneable, and Serializable.
回答4:
Of course... Almost all classes implements several interfaces. On any page of java documentation on Oracle you have a subsection named "All implemented interfaces".
Here an example of the Date class.
回答5:
Yes, it is possible. This is the catch: java does not support multiple inheritance, i.e. class cannot extend more than one class. However class can implement multiple interfaces.
回答6:
It is true that a java class can implement multiple interfaces at the same time, but there is a catch here. If in a class, you are trying to implement two java interfaces, which contains methods with same signature but diffrent return type, in that case you will get compilation error.
interface One
{
int m1();
}
interface Two
{
float m1();
}
public class MyClass implements One, Two{
int m1() {}
float m1() {}
public static void main(String... args) {
}
}
output :
prog.java:14: error: method m1() is already defined in class MyClass
public float m1() {}
^
prog.java:11: error: MyClass is not abstract and does not override abstract method m1() in Two
public class MyClass implements One, Two{
^
prog.java:13: error: m1() in MyClass cannot implement m1() in Two
public int m1() {}
^
return type int is not compatible with float
3 errors
回答7:
An interface can extend other interfaces. Also an interface cannot implement any other interface. When it comes to a class, it can extend one other class and implement any number of interfaces.
class A extends B implements C,D{...}
来源:https://stackoverflow.com/questions/21263607/can-a-normal-class-implement-multiple-interfaces