Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple interfaces in a java class - which gets used for method calls?

If I have a class that implements two interfaces and I send that class to an overloaded method that accepts either interface; which variant of the method will be called?

In other words, if I have something like this:

interface A {}
interface B {}

class C implements A, B { }

class D
{
    public static void doThings(A thing){ System.out.println("handling A");}
    public static void doThings(B thing){ System.out.println("handling B");}

    public static void main(String[] args) {
        doThings(new C());
    }
}

And I send my class C to the method/s in D:

doThings(C);

Which method should be called? Does the Java standard cover this?

like image 581
Micheal Hill Avatar asked Mar 26 '14 23:03

Micheal Hill


2 Answers

You will get a compiler error, because multiple methods match, namely, both doThings methods.

The JLS does cover this, in Section 15.12.2.5. It covers how to resolve which method is applicable for an expression that calls a method.

Otherwise, we say that the method invocation is ambiguous, and a compile-time error occurs.

This occurs after multiple methods are found that match, one method is not any more "specific" than another, and none are abstract.

like image 199
rgettman Avatar answered Sep 18 '22 11:09

rgettman


This raises a compile time error.
"The method doThings is ambiguous for the type D"
So this is your answer.

interface AAA { }
interface BBB { }

class C implements AAA, BBB {  }

public class D
{
    public static void doThings(AAA thing){

    }
    public static void doThings(BBB thing){

    }

    public static void main(String[] args){
        C x = new C();
        D.doThings(x);
    }
}

Here is the exact error:

C:\Programs\eclipse\workspace\TEST\src>javac D.java
D.java:17: reference to doThings is ambiguous, both method doThings(AAA) in D and method doThings(BBB) in D match
        D.doThings(x);
         ^
1 error

Still, note that if you define x as AAA x = new C();
or as BBB x = new C();, then it compiles OK. Now
the type of the x reference (AAA or BBB) makes
this version unambiguous.

like image 25
peter.petrov Avatar answered Sep 20 '22 11:09

peter.petrov