【问题标题】:Is possible to set a default value and then change the value in a constructor可以设置默认值,然后在构造函数中更改值
【发布时间】:2016-06-17 10:44:43
【问题描述】:
class Person {
   private String name;
   private String sex="male";
   public Person(String name) {
       this.name = name;
   }
   public String getSex(){return this.sex;}
}

在上面的类中,如果我想设置sex的默认值。可以吗? 那么,如果我想创建新的Person,下面的代码好吗?

Person p = new Person("mike");
String sex = p.getSex();

【问题讨论】:

  • 试用并报告。

标签: java constructor default-value


【解决方案1】:

您可以在 Java 中链接构造函数以赋予某些值默认值。

例如,这里有一个带有名字的构造函数和一个带有名字和性别的构造函数。

public class Person {
    private String name;
    private String sex;

    public Person(String name, String sex) {
        this.name = name;
        this.sex = sex;
    }

    public Person(String name) {
        this(name, "male");
    }

    // getters/setters here
}

如果您的对象有很多可能是可选的属性,您应该考虑使用Builder pattern 而不是标准构造函数。

【讨论】:

  • 请注意,this(whatever) 是一个特殊关键字,表示“使用这些参数调用此其他构造函数”。据我所知,它只在构造函数中有效。
【解决方案2】:

通过将字段定义为 final 并仅通过构造函数分配值来使您的类线程安全总是好的。

class Person {
   private final String name;
   private final String sex;
   public Person(String name, String sex) {
       this.name = name;
       this.sex = sex;
   }
   public String getName() { return this.name; }
   public String getSex(){return this.sex;}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 2020-12-31
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    相关资源
    最近更新 更多