来自构造函数的Java调用构造函数 [英] Java call constructor from constructor

查看:254
本文介绍了来自构造函数的Java调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个构造函数

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?

推荐答案

你为什么不做这个(a,a + 10)而不是?

注意 this() super()必须是构造函数中的第一个语句(如果存在)。但是,你仍然可以在参数中做逻辑。如果你需要做复杂的逻辑,可以通过在参数中调用类方法来实现:

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:

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

这篇关于来自构造函数的Java调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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