在 Java 中处理多个构造函数的最佳方法 [英] Best way to handle multiple constructors in Java

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

问题描述

我一直想知道在 Java 中处理多个构造函数的最佳(即最干净/最安全/最有效)的方法是什么?尤其是在一个或多个构造函数中并非所有字段都被指定时:

I've been wondering what the best (i.e. cleanest/safest/most efficient) way of handling multiple constructors in Java is? Especially when in one or more constructors not all fields are specified:

public class Book
{

    private String title;
    private String isbn;

    public Book()
    {
      //nothing specified!
    }

    public Book(String title)
    {
      //only title!
    }

    ...     

}

未指定字段怎么办?到目前为止,我一直在类中使用默认值,以便字段永远不会为空,但这是一种好"的做事方式吗?

What should I do when fields are not specified? I've so far been using default values in the class so that a field is never null, but is that a "good" way of doing things?

推荐答案

稍微简化的答案:

public class Book
{
    private final String title;

    public Book(String title)
    {
      this.title = title;
    }

    public Book()
    {
      this("Default Title");
    }

    ...
}

这篇关于在 Java 中处理多个构造函数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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