问一道有关overload的题

zhgzhang 2003-05-21 11:16:19
我觉得3) protected void amethod (long l){}不是正确答案,原因是long和int分不清,这是http://www.jchq.net/certkey/0104certkey.htm上一道例题


Question 1)
Given the following class definition
public class Upton{
public static void main(String argv[]){
}

public void amethod(int i){}
//Here
}

Which of the following would be legal to place after the comment //Here ?
1) public int amethod(int z){}
2) public int amethod(int i,int j){return 99;}
3) protected void amethod(long l){ }
4) private void anothermethod(){}

Answer to Question 1)
2) public int amethod(int i, int j) {return 99;}
3) protected void amethod (long l){}
4) private void anothermethod(){}
Option 1 will not compile on two counts. One is the obvious one that it claims to return an integer. The other is that it is effectively an attempt to redefine a method within the same class. The change of name of the parameter from i to z has no effect and a method cannot be overridden within the same class.
...全文
67 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
heface 2003-05-26
  • 打赏
  • 举报
回复
答案很对啊
zhgzhang 2003-05-22
  • 打赏
  • 举报
回复
一套题的解析中看到的

此题涉及方法重载(overload),方法重写(override)以及类派生时方法重写的规则。方法重载的规则是:一、参数列表必须不同,个数的不同完全可以,如果个数相同则参数类型的不同不能引起歧意,例如int 和long,float和double就不能作为唯一的类型不同;二、返回值可以不同,但是不能是重载时唯一的不同点(这点和c++中不同,c++中返回类型必须一致)。方法重写发生在类继承时,子类可以重写一个父类中已有的方法,必须在返回类型和参数列表一样时才能说是重写,否则就是重载,java中方法重写的一个重要而且容易被忽略的规则是重写的方法的访问权限不能比被重写的方法的访问权限低!重写的另一个规则是重写的方法不能比被重写的方法抛弃(throws)更多种类的异常,其抛弃的异常只能少,或者是其子类,不能以抛弃异常的个数来判断种类,而应该是异常类层次结果上的种类。此题中答案a的错误就是重写的访问权限比被重写的方法的低,而b,c都属于重载,d的错误在于比被重写的方法抛弃了更多种类的异常。
zhgzhang 2003-05-22
  • 打赏
  • 举报
回复
那float和double呢
lishifeng 2003-05-22
  • 打赏
  • 举报
回复
long和int是可以分清的,例如
amethod(1); --> public void amethod(int);
amethod(1L); --> protected void amethod(long);
最佳匹配:首先是完全匹配,其次是隐式转换。

51,407

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧