招商依云曲江最新房价:java的重载实例?

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/24 11:26:30
我这里有一个java重载的实例。可是没办法编译。请大家帮忙看一下 问题出在了哪里。 谢谢!
代码如下:
class Try{
int x;
int y;
Try(int m){
x=m;
y=m;
}
void Try(int m,int n){
x=m;
y=n;
}
int compute( ){
return x+y;
}
int compute(int mul){
return (x+y)*mul;
}
}
class PrintTry{
public static void main(String[] args){
Try tryone;
Try trytwo;
tryone=new Try(5);
trytwo=new Try(10,10);
System.out.println("tryone调用compute()计算,值为:"+tryone.compute( ));
System.out.println("tryone调用compute(3)计算,值为:"+tryone.compute(3));
System.out.println("trytwo调用compute()计算,值为:"+trytwo.compute());
System.out.println("trytwo调用compute(3)计算,值为:"+trytwo.compute(3));
}
}
编译的时候总是提醒trytwo=new Try(10,10);部分除了错。


void Try(int m,int n){
x=m;
y=n;
}
中的void 去掉,返回void 也算返回一种类型,而构造方法是没有返回类型的,因此编译器不把其看做构造方法,更不用提构造方法的重载了

你的函数名不要和类名同名``要不然编译器会认为你这个函数是构造函数而构造函数是没有返回类型的`