所以在java中你不能有不同的返回和参数的重复方法名称? [英] so in java you can't have duplicate method names with different return and params?

查看:118
本文介绍了所以在java中你不能有不同的返回和参数的重复方法名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Java中使用两个具有相同名称但不同参数和返回类型的方法?看起来它是一个很好的方法来推广一个简单的getter和setter ..你可以用构造函数来做到这一点,为什么不使用常规方法?例如

Is it possible to have two methods with the same name but different parameters and return types in Java? Seems like it would be a good way to generalize a simple getter and setter.. You can do that with constructors why not with regular methods ? for example

为什么不能这样做..

why not be able to do ..

int getVal() {

return int;
}

boolean getVal() {

return true;

}

setVal(int a) {
}

setVal(boolean a) {

}


推荐答案

因为那时编译器无法弄明白:

Because then the compiler would be unable to figure out:


setVal(getVal());

它应该调用bool还是int版本?

should it call the bool or int version?

这篇关于所以在java中你不能有不同的返回和参数的重复方法名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆