在Java 8中重载默认接口方法

时间:2017-08-20 14:36:35

标签: interface java-8 default-method

为什么不能在Java 8中的接口中重载默认方法。

2 个答案:

答案 0 :(得分:2)

问题中的假设(“为什么不能在Java 8中的接口中重载默认方法”)是不正确的。完全可以重载接口的默认方法。例如,考虑下面编译得很好的代码:

public interface SomeInterface {
    default void print(String s) {
        System.out.println(s);
    }
}

public class SomeClass implements SomeInterface {
    /**
     * Note the this overloads {@link SomeInterface#print(String)}, 
     * not overrides it!
     */
    public void print(int i) {
        System.out.println(i);
    }
}

答案 1 :(得分:1)

我们可以在接口和实现类中为重载的默认方法提供定义。请看下面的代码: -

public class DefaultMethodConflicts2 implements DefInter3,DefInter2 {
public static void main(String[] args) {
        new DefaultMethodConflicts2().printme();
        new DefaultMethodConflicts2().printmeNew();
        new DefaultMethodConflicts2().printme("ashish");
    }

/*
 If we do not write below method than this step result in error :-
 //public class DefaultMethodConflicts2 implements DefInter3,DefInter2 {  // <-- error occur --> Duplicate default methods named printme with the parameters () and ()
  *  are inherited from  the types DefInter2 and DefInter3. To check this comment below method.
 */ 
 public void printme() {
        DefInter3.super.printme(); // <-- it require to compile the class
    }

 public void printmeNew() {
        System.out.println(" From DefaultMethodConflicts2 :: printmeNew()"); // <--     compile successfully and execute -- line 19
                                                                             //  <----  overloading default method printmeNew() in implementing class as well.
    }
}


interface DefInter3 {
    default void printme() {System.out.println("from printme3()");}   
    default void printmeNew() {System.out.println("fFrom DefInter3:printmeNew()");}  //  <------ if DefaultMethodConflicts2::printmeNew() at line 19 is commented out
                                                                          //            then it will executes.
}

interface DefInter2 {
    default void printme() {System.out.println("From DefInter2::()");} 
    default void printme(String name) {System.out.println("From DefInter2::printme2(String name) "+name);} // <--- Overloading printme() here in interface itself
}