2

If I attempt to overload the method flexiPrint() in a class Varargdemo then it generates a compile time error. The compiler treats the following signatures the same:

public static void flexiPrint(Object... data){}
public static void flexiPrint(Object[] data){}

Can someone explain to me why they are treated the same? I haven't been able to find the answer.

3 Answers 3

3

Object... is nothing but it is an array, that means same as defining Object[]

... (three dots) represents varargs in java.

We usually see this signature in main method like main(String... args)

So, having more than one method with same signature is not allowed in a class (compile time error). That is why you are seeing compile time error.

Sign up to request clarification or add additional context in comments.

Comments

3

They are the same "under the hood". varargs (the ...) passes an array as a parameter:

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs.

You can find it in the documentation here .

Comments

2

Variable Length Arguments, like Object... are syntactic sugar. When used, for example:

flexiPrint("apple", "peach", "plum");

Then "apple", "peach", "plum" are actually turned into: `Object[]{"apple", "peach", "plum"}.

2 Comments

Method overloading is specifying a second method with the same name, but different return type and/or parameters. Method overriding is what you describe in your answer (overriding super-class methods).
Your last statement about the signatures being identical was still true, but thanks for the correction :) +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.