重载构造函数调用其他构造函数,但不作为第一个语句 [英] Overloaded constructor calling other constructor, but not as first statement

查看:275
本文介绍了重载构造函数调用其他构造函数,但不作为第一个语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想做的是这样的:

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.

这种情况的常见解决方案是什么?
我无法计算arg2和arg3在行。我想也许可以创建一个构造辅助方法,它将进行实际构造,但我不确定它是如此漂亮......

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

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

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.

推荐答案

通常使用另一种常用方法 - 如你所建议的建筑助手。

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

替代方案是工厂式方法,其中您有 MyClassFactory 它给你 MyClass 个实例, MyClass 只有一个构造函数:

The alternative is a Factory-style approach in which you have a MyClassFactory that gives you MyClass instances, and MyClass has only the one constructor:

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.

这篇关于重载构造函数调用其他构造函数,但不作为第一个语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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