Piyush Kothari
Piyush Kothari

Reputation: 61

Overload Default Interface Method in Java 8

Why is it not possible to overload default methods in Interface in Java 8.

Upvotes: 0

Views: 1943

Answers (2)

Ashish Sharma
Ashish Sharma

Reputation: 672

We can provide definition for overloaded default method both in interface and in implementing class. Please have a look in below code :-

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
}

Upvotes: 1

Mureinik
Mureinik

Reputation: 311308

The assumption in the question ("Why is it not possible to overload default methods in Interface in Java 8") is just not true. It is perfectly possible to overload an interface's default method. E.g., consider the following code which compiles just fine:

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

Upvotes: 4

Related Questions