Can a normal Class implement multiple interfaces?

后端 未结 8 1078
春和景丽
春和景丽 2021-01-31 01:34

I know that multiple inheritances between Interfaces is possible, e.g.:

public interface C extends A,B {...} //Where A, B and C are Interfaces

8条回答
  •  春和景丽
    2021-01-31 02:23

    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
    

提交回复
热议问题