当我们重载构造函数时,Oracle 引用并没有说明这个关键字的最佳实践。任何人都可以建议它的最佳做法吗?

选项 1:委托(delegate)给另一个构造函数

public class A { 
    private int x, y, z, p;   
 
    public A() { 
        this(1,1,1,1); 
    } 
 
    public A(int x, int y, int z, int p) { 
        this.x = x; 
        this.y = y; 
        this.z = z; 
        this.p = p; 
    } 
} 



选项2:设置每个字段而不是委托(delegate)
public class A { 
    private int x, y, z, p;   
 
    public A() { 
        this.x = 1; 
        this.y = 1; 
        this.z = 1; 
        this.p = 1; 
    } 
 
    public A(int x, int y, int z, int p) { 
        this.x = x; 
        this.y = y; 
        this.z = z; 
        this.p = p; 
    } 
} 

请您参考如下方法:

第一个是最好的。

它在官方文档和许多书籍中被多次引用。这是方法链接的一个特定情况,或者正如评论中的其他人所指出的那样,伸缩构造函数。它们允许您编写更少的代码并且不重复自己(DRY)。

你可以在像 Apache Commons 这样的实体库中找到这种方法。以及其他平台的最佳实践。最后是名著 Thinking in Java,在 Initialization & Cleanup chapter 中使用这种形式(从构造函数部分调用构造函数)。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!