Java构造函数设计 [英] Java constructor design

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

问题描述

我在读一个开源代码,并且有一个像这样设计的构造函数:

I was reading an open-source code, and there was a constructor designed like this:

public class FeatureSequence2FeatureVector extends Pipe implements Serializable
{
    boolean binary;

    public FeatureSequence2FeatureVector (boolean binary)
    {
       this.binary = binary;
     }

    public FeatureSequence2FeatureVector ()
    {
       this (false);
    }
 }

这可能只是一个微不足道的偏好,我会这样做:

This may be just a trivial preference matter, but what I would do is like this:

public class FeatureSequence2FeatureVector extends Pipe implements Serializable
 {
    boolean binary = false;

    public FeatureSequence2FeatureVector (boolean binary)
    {
       this.binary = binary;
     }
     public FeatureSequence2FeatureVector ()
     {
     }
 }

通过为类变量分配初始值,是否有可能的负面结果?
这两种方式几乎是同样优选的吗?

Is there any possible negative outcome by assigning an initial value for class variables? Would the two ways be almost equally preferred?

推荐答案

这两种方式并不是首选。

These two ways are not equally preferred.

原始方式确保所有初始化都通过主构造函数。第二种方式允许用于初始化对象的不同路径。

The original way makes sure that all initialization goes through a primary constructor. The second way allows different paths for initializing an object.

在您的示例中,它非常简单。但是使用第二种方法,一个构造函数可以被修改为不同于另一个构造函数做的事情,从而如何初始化对象取决于选择哪个构造函数。

In your example it's pretty trivial. But with the second way one constructor could be modified to do something different from how the other constructor did things, whereupon how your objects are initialized depends on which constructor was chosen.

此问题显示了允许不同路径导致问题的情况。

This question shows a situation where allowing different paths caused trouble.

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

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