Implementing two interfaces with two default methods of the same signature in Java 8

前端 未结 6 546
悲哀的现实
悲哀的现实 2020-11-30 06:10

Suppose I have two interfaces:

public interface I1
{
    default String getGreeting() {
        return \"Good Morning!\";
    }
}

public interface I2
{
             


        
6条回答
  •  天命终不由人
    2020-11-30 06:51

    If a class implements 2 interfaces both of which have a java-8 default method with the same signature (as in your example) the implementing class is obliged to override the method. The class can still access the default method using I1.super.getGreeting();. It can access either, both or neither. So the following would be a valid implementation of C1

    public class C1 implements I1, I2{
        public static void main(String[] args)
        {
            System.out.println(new C1().getGreeting());
        }
    
        @Override //class is obliged to override this method
        public String getGreeting() {
            //can use both default methods
            return I1.super.getGreeting()+I2.super.getGreeting();
        }
    
        public String useOne() {
            //can use the default method within annother method
            return "One "+I1.super.getGreeting();
        }
    
        public String useTheOther() {
            //can use the default method within annother method
            return "Two "+I2.super.getGreeting();
        }
    
    
    }
    

提交回复
热议问题