Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading methods in Java [duplicate]

What conditions must be met so that two methods correctly qualify as overloaded methods?

Is it that two methods must at least differ in their list of arguments such as

public void A() { //... }
public void A(int val) { //.. } 

Hence, a mere change in return-type and/or access modifier wont make two overloaded methods?

like image 454
Andrew Tobey Avatar asked Feb 15 '15 20:02

Andrew Tobey


2 Answers

You are right. Return types and access modifiers are not qualifying factors for method overloading. What qualifies methods as being overloaded are the parameters that are passed, i.e, either the type of parameters, number of parameters passed or both.

like image 56
happyHelper Avatar answered Sep 28 '22 16:09

happyHelper


The rules are far from arbitrary: say you had

String a() {}
Date a() {}

How would you call a? Let's see:

Object o = a(); // which a() is called?

Methods differring only by access modifier would make even less sense: they would be two copies of the same method, but with different behavior.

So the actual rules define the method signature to consist of those parts which are fixed at each call site: name and parameter types. A class may not have two methods with the same signature.

like image 25
Marko Topolnik Avatar answered Sep 28 '22 16:09

Marko Topolnik