java Java从构造函数调用构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12880443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java call constructor from constructor
提问by user1284151
I have a constructor
我有一个构造函数
private Double mA;
private Double mB;
Foo(Double a) {
mA = a;
mB = a + 10;
}
Foo(Double a, Double b) {
mA = a;
mB = b;
// some logic here
}
if I make a call to second constructor like this:
如果我像这样调用第二个构造函数:
Foo(Double a) {
Double b = a + 10;
this(a, b);
}
than compiler tells me, that constructor should be the first statement. So do I need to copy all logic from the second constructor to first one?
比编译器告诉我,构造函数应该是第一条语句。那么我是否需要将所有逻辑从第二个构造函数复制到第一个构造函数?
回答by nneonneo
Why don't you just do this(a, a+10)
instead?
你为什么不做this(a, a+10)
呢?
Note that this()
or super()
must be the first statement in a constructor, if present. You can, however, still do logic in the arguments. If you need to do complex logic, you can do it by calling a class method in an argument:
请注意,this()
orsuper()
必须是构造函数中的第一条语句(如果存在)。但是,您仍然可以在参数中进行逻辑处理。如果需要做复杂的逻辑,可以通过在参数中调用类方法来实现:
static double calculateArgument(double val) {
return val + 10; // or some really complex logic
}
Foo(double a) {
this(a, calculateArgument(a));
}
Foo(double a, double b) {
mA = a;
mB = b;
}
回答by Rohit Jain
If you use this()
or super()
call in your constructor to invoke the other constructor, it should always be the first statement in your constructor.
如果您在构造函数中使用this()
或super()
调用来调用另一个构造函数,则它应该始终是构造函数中的第一条语句。
That is why your below code does not compile: -
这就是为什么您的以下代码无法编译的原因:-
Foo(Double a) {
Double b = a + 10;
this(a, b);
}
You can modify it to follow the above rule: -
您可以修改它以遵循上述规则:-
Foo(Double a) {
this(a, a + 10); //This will work.
}
回答by Subhrajyoti Majumder
Invocation of another constructor must be the first line in the constructor.
另一个构造函数的调用必须在构造函数的第一行。
You can call explicit constructor invocationlike -
您可以调用显式构造函数调用,如 -
Foo(Double a) {
this(a, a+10);
}