Hi All,

I came across this question in Cathy Siera SCJP book and the answer is really Strange and i dont understand. The question is below.

class A { }
class B extends A { }

public class Comingthru {

static String s ="-";

public static void main(String[] args) {

A[] aa = new A[2];
B[] ba = new B[2];

sifter(aa);
sifter(ba);
sifter(7);
System.out.println(s);

}

static void sifter(A[]... a2) { s += "1"; }
static void sifter(B[]... b1) { s += "2"; }
static void sifter(B[] b1)    { s += "3"; }
static void sifter(Object o)  { s += "4"; }

}

** I thought the answer is -444 but in the book said answer is -434 and the explanation given is "-434 is correct. In general, overloaded var-args are chosen last. Remember that arrays are objects. Finally an int can be boxed into an Integet and widened into Object " **

** My question is if the first method invocation went to sifter(object o) and the second should also go to sifter(object O) right ? since both are arrays as per the explanation given in the book .Then why the 2nd invocation went to sifter(B[] b1) ?.

Please explain

Recommended Answers

All 2 Replies

The answer. as always, is in the doc, the Java Language Spec in this case. Section 15.12.2.5.

15.12.2.5 Choosing the Most Specific Method
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one ... The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
<followed by pages of really difficult stuff>

The first call goes to sifter(Object) because only A[]... and Object are applicable, and A[]... is considered less specific than Object.
The second call goes to sifter(B[]) because B[]..., B[], and Object are applicable, and B[] is nore specific than Object

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.