0

我用多个构造函数扩展了一个类。我在我的子类中添加了一个 final 字段,当然需要在我自己的构造函数中对其进行初始化。

问题是我不想重新实现(大多数)超类的构造函数,所以我想做这样的事情:

public myConstructor(Object... params){
    super(params);
    try{
        this.finalField = "backup value";
    }
    catch(someException e){

    }
}

这可能以某种方式或其他方式吗?

编辑:我意识到这种情况永远不会发生,因为超类构造函数永远不会调用我自己的构造函数。

4

2 回答 2

2

To simplify process of object initialization, usually I use the following solutions:

  • You could create a static-factory method which will be create object (and throw exceptions if needed) instead of constructors and provide common initialization functionality in reusable private method.
  • Also you could use Builder-pattern instead of multiple constructors. http://en.wikipedia.org/wiki/Builder_pattern
于 2012-06-19T08:24:44.113 回答
1

Have all your constructors call one single constructor that sets the final field.

于 2012-06-19T08:25:00.893 回答