2017-08-20 13 views

答えて

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); 
    } 
} 
+0

ありがとうMureinik。議論を終わらせる。コンパイルエラーが発生したIDEの問題がありました。 パッケージjava8Interface; @FunctionalInterface パブリックインターフェイスMyInterface { \t \tデフォルトのボイドディスプレイ(文字列名) \t { \t \tのSystem.out.println( "あなたの名前は:" +名)。 \t} \t \tデフォルトのボイドディスプレイ(文字列firstNameの、文字列の姓) \t { \t \tのSystem.out.printlnは( "あなたのフルネームは:" + firstNameの+ "" +姓)。 \t} \t \t public void display(); \t } –

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 
}