overloading methods in Java [duplicate]

自古美人都是妖i 提交于 2020-05-27 05:11:08

问题


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?


回答1:


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.




回答2:


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.




回答3:


you are right brother ,change in access modifier and return type won't make methods overloaded . The point is that methods that have same name and different signatures(arguments) are said to be overloaded . This is the sufficient condition for making methods overloaded .




回答4:


Th only rule is that overloaded methods have to have the same name and different argument types from the JVM perspective, e.g. you cannot have the following 2 methods:

public int methodA(int... array);
public void methodA(int[] array);

Does not matter on visibility modifiers or return types.



来源:https://stackoverflow.com/questions/28531065/overloading-methods-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!