[英]Constructor Method overload Java
Very simple Rational class I'm trying to create. 我正在尝试创建非常简单的Rational类。
If, in the main methods, one calls Rational(2)
then num = 2
and den = 1
如果在主要方法中,一个调用Rational(2)
则num = 2
和den = 1
If one calls Rational(2, 4)
then num = 2
and den = 4
如果一个调用Rational(2, 4)
则num = 2
和den = 4
Here is my code: 这是我的代码:
public class Rational {
public long num;
public long den;
Rational(long arg1, long arg2){
num = arg1;
den = arg2;
}
Rational(long arg1){
long x = 1;
Rational(arg1, x); //Rational(long, long) is undefined for type Rational
}
}
I have commented the error message I have no idea how to fix. 我已评论该错误消息,但我不知道如何解决。
Any suggestions? 有什么建议么?
您需要使用this
关键字,但它必须是构造函数中的第一条语句,因此在此之前将无法定义x
this(arg1, 1);
this(arg1, 1);
You call the other constructor using the this
keyword, similar to how you would use super
. 您可以使用this
关键字调用另一个构造函数,类似于您使用super
。 It must also be the first statement in the constructor body. 它也必须是构造函数主体中的第一条语句。 Since it is first, you will have to change the way you pass in x
in your example. 因为它是第一个,所以您将必须更改示例中传递x
的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.