简体   繁体   English

来自构造函数的Java调用构造函数

[英]Java call constructor from constructor

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? 那么我需要将所有逻辑从第二个构造函数复制到第一个构造函数吗?

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. 请注意, this()super()必须是构造函数中的第一个语句(如果存在)。 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: 如果需要执行复杂的逻辑,可以通过在参数中调用类方法来实现:

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;
}

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.
}

Invocation of another constructor must be the first line in the constructor. 另一个构造函数的调用必须是构造函数中的第一行。

You can call explicit constructor invocation like - 您可以调用显式构造函数调用,如 -

Foo(Double a) {
  this(a, a+10);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM