在构造函数中委托给另一个构造函数(使用this())是好还是坏 [英] Is it good or bad to delegate to another constructor (using this()) within a constructor

查看:139
本文介绍了在构造函数中委托给另一个构造函数(使用this())是好还是坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们重载构造函数时,Oracle参考资料没有介绍关键字的最佳做法。

Oracle reference doesn't tell about best practice of this keyword while we overload constructors. Can anyone suggest the best practice for it?

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

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


推荐答案

第一个是最好的。

它在官方文档和许多书中被多次引用。这是方法链接的具体情况,或者如注释中注释的其他伸缩构造函数

It is referenced multiple times in the offical docs and in many books. It is a specific case of method-chaining or, as others noted in the comments, telescoping constructors. They allows you to write less code and to not repeat yourself (DRY).

你可以在实体库中找到这个方法,例如 Apache Commons 以及其他平台的最佳做法。最后,着名的Thinking in Java一书中,在初始化&清理章从构造函数调用构造函数部分)。

You can find that approach everywhere in solid libraries like Apache Commons and also in the best practices of other platforms. Finally, the famous book Thinking in Java, use this form in the Initialization & Cleanup chapter (Calling constructors from constructors section).

这篇关于在构造函数中委托给另一个构造函数(使用this())是好还是坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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