java 重载构造函数调用其他构造函数,但不是作为第一条语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3386136/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:35:14  来源:igfitidea点击:

Overloaded constructor calling other constructor, but not as first statement

javaconstructoroverloading

提问by David B

I'm having some trouble using multiple constructors in java.

我在 java 中使用多个构造函数时遇到了一些麻烦。

what I want to do is something like this:

我想做的是这样的:

public class MyClass {

 // first constructor
 public MyClass(arg1, arg2, arg3) {
  // do some construction
 }

 // second constructor
 public MyClass(arg1) {
      // do some stuff to calculate arg2 and arg3
      this(arg1, arg2, arg3);
    }
}

but I can't, since the second constructor cannot call another constructor, unless it is the first line.

但我不能,因为第二个构造函数不能调用另一个构造函数,除非它是第一行。

What is the common solution for such situation? I can't calculate arg2 and arg3 "in line". I thought maybe creating a construction helper method, that will do the actual construction, but I'm not sure that's so "pretty"...

这种情况的通用解决方案是什么?我无法“在线”计算 arg2 和 arg3。我想也许会创建一个构造辅助方法,它会进行实际的构造,但我不确定那是否如此“漂亮”......

EDIT: Using a helper method is also problematic since some of my fields are final, and I can't set them using a helper method.

编辑:使用辅助方法也有问题,因为我的一些字段是最终的,我无法使用辅助方法设置它们。

回答by Matt Mitchell

Typically use another common method - a "construction helper" as you've suggested.

通常使用另一种常用方法 - 如您所建议的“构造助手”。

public class MyClass { 

    // first constructor 
    public MyClass(arg1, arg2, arg3) { 
      init(arg1, arg2, arg3); 
    } 

    // second constructor 
    public MyClass(int arg1) { 
      // do some stuff to calculate arg2 and arg3 
      init(arg1, arg2, arg3); 
    } 

    private init(int arg1, int arg2, int arg3) {
      // do some construction 
    }
} 

The alternative is a Factory-style approach in which you have a MyClassFactorythat gives you MyClassinstances, and MyClasshas only the one constructor:

另一种方法是工厂风格的方法,在这种方法中,您有一个MyClassFactory可以为您提供MyClass实例的方法,并且MyClass只有一个构造函数:

public class MyClass { 

    // constructor 
    public MyClass(arg1, arg2, arg3) { 
      // do some construction 
    } 
} 

public class MyClassFactory { 

    public static MyClass MakeMyClass(arg1, arg2, arg3) { 
      return new MyClass(arg1, arg2, arg3);
    } 

    public static MyClass MakeMyClass(arg1) { 
      // do some stuff to calculate arg2 and arg3 
      return new MyClass(arg1, arg2, arg3);
    } 
} 

I definitely prefer the first option.

我绝对更喜欢第一个选项。

回答by Gaim

Next possible solution is Factory method. These static methods can be overloaded and after calculation they can call the private / protected constructor

下一个可能的解决方案是工厂方法。这些静态方法可以重载,计算后它们可以调用私有/受保护的构造函数

public class MyClass {

    private MyClass( arg1, arg2, arg3 ) {
         // do sth
    }

    public static MyClass getInstance( arg1 ) {
         // calculate arg2,3
        return new MyClass( arg1, arg2, arg3 );
    }

    public static MyClass getInstance( arg1, arg2, arg3 ) {
        return new MyClass( arg1, arg2, arg3 );
    }
}

EDIT:This method is also ideal when you have a final fields

编辑:当您有最终字段时,此方法也是理想的

回答by Jorn

Although I prefer the factory method option pointed to by several other answers, I wanted to suggest another option: You can use static methods to do the calculation of your other parameters:

虽然我更喜欢其他几个答案指向的工厂方法选项,但我想建议另一个选项:您可以使用静态方法来计算其他参数:

public class MyClass {
    public MyClass(int arg1, int arg2, int arg3) {
        // do some construction
    }

    public MyClass(int arg1) {
      //call to this() must be the first one
      this(arg1, calculateArg2(arg1), calculateArg3());
      //you can do other stuff here
    }

    private static int calculateArg2(int arg1) {
      //calc arg2 here
    }

    private static int calculateArg3() {
      //calc arg3 here
    }
}

回答by Bozho

The helper and factory options are very good.

助手和工厂选项非常好。

There is another one:

还有一个:

public MyClass(int arg1) {
    this(arg1, calculateArg2(), calculateArg3());
}

private static int calculateArg2() {..}
private static int calculateArg3() {..}

回答by Tassos Bassoukos

Use marker values for 'missing'

对“缺失”使用标记值

public class MyClass {
 public MyClass(arg1, arg2, arg3) {
  // do some stuff to calculate arg2 and arg3 if they are the missing values
  // do some construction
 }
 public MyClass(arg1) {
   this(arg1, null, null);
 }
}

For best results, make the 'general' constructor protectedor private.

为获得最佳结果,请使用“通用”构造函数protectedprivate.

回答by naikus

Another way is this:

另一种方法是这样的:

public class MyClass {

  // first constructor
  public MyClass(arg1, arg2, arg3) {
   // do some construction
   doSomeStuffToArg3Arg3(arg2, arg3)
  }

  // second constructor
  public MyClass(int arg1) {
      this(arg1, arg2, arg3);
  }

  private void doSomeStuffToArg3Arg3(int arg2, int arg3) {
     // do some stuff to calculate arg2 and arg3
  }
}

回答by rsp

As an alternative to the answers given, the simplest way is to refactor the argument calculation to the 3 argument constructor;

作为给出答案的替代方案,最简单的方法是将参数计算重构为 3 参数构造函数;

public class MyClass {

    // first constructor
    public MyClass(arg1, arg2, arg3) {
        if (null == arg2) {
            // calculate arg2
        }
        if (null == arg3) {
            // calculate arg3
        }
        // do some construction
    }

    // second constructor
    public MyClass(arg1) {
        this(arg1, null, null);
    }
}

回答by DixonD

You can move the code of MyClass(arg1, arg2, arg3)into helper method (name it Initor something else ) and then call this method in both constructors.

您可以将 的代码MyClass(arg1, arg2, arg3)移入辅助方法(命名Init或其他),然后在两个构造函数中调用此方法。

回答by sleske

You could create a factory methodwhich calls the constructor:

您可以创建一个调用构造函数的工厂方法

public class MyClass { 

    // first constructor 
    public MyClass(arg1, arg2, arg3) { 
    // do some construction

    } 

    // second constructor as factory method
    public static createMyClassAndDoFunkyStuff(int arg1) { 
      // do some stuff to calculate arg2 and arg3 
      return new MyClass(arg1, arg2, arg3); 
    } 

}