'Why do I get an ambiguity error in this code?
Let's say we have these 3 classes:
class A { }
class B extends A { }
public class App {
static void f(int i, A a) { }
static void f(float j, B b) { }
static public void main() {
int i = 0;
B b = new B();
App.f(i, b);
}
}
This produces the error:
App.java:11: error: reference to f is ambiguous
App.f(i, b);
^
both method f(int,A) in App and method f(float,B) in App match
1 error
Why does it not choose the type f(int, A) since i is an integer?
Solution 1:[1]
Two things:
- Type widening (1st parameter)
- Inheritance (2nd parameter)
Type widening: float is "wider" type than int therefore passed int value can be easily packed into bigger float box. It will not work in case, when we would like to "pack" float into int, as we can potentially lost floating point.
In provided case, having an int we can potentially pass it two both functions.
fFloat(float f){}
int intValue = 221;
fFloat(intValue); // inside f, intValue is treated as 221.0
fInt(int i){}
float floatVal = 221.221;
fInt(floatVal); // what should compiler do with remaining .221 part?
Inheritance: A is a base class, while B is one of subclasses of A. So, when we declare method parameter as a base class, we can provide there both base class and its instance (but we will be able to use B b instance inside f(int i, A a) like type A. Hence, we can pass B b = new B(); to both methods as well.
class A {
public void f() {}
}
class B extends A {
public void g() {}
}
fA(A a){}
B bInst = new B();
fA(bInst); // you can refer only to f() method, not g()
fB(B b){}
A aInst = new A();
fB(aInst); // you cannot do this, as subclass can have some additional
// stuff, that superclass does not have
//but even
A aInstBImpl = new B();
fB(aInstBImpl); // will not work without explicit casting as it is
// kind of A instance with B implementation - here polymorphism comes into action
Since all 2 parameters (from 2 possible) can suit to both methods without any explicit "action taken", the ambiguity error arises.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R-tooR |
