有办法在Java中使属性变为可选吗?

huangapple go评论83阅读模式
英文:

Is there a way of making optional atributes in java?

问题

我需要在Java中编写这个类。我考虑过创建一堆构造函数,但我不认为那是最好的方法。我想知道Java是否有某种可选参数或属性,以使这更简单。

英文:

I need to code this class in java. I thought of making a bunch of constructors but i dont think thats the best way to do it. Id like to know if java has some sort of optional parameters or attributes to make this simpler.

答案1

得分: 0

你可以使用一个带有可变参数(varargs)的构造函数来实现,因为你的类中所有字段的类型都是 String

public class Address {
    private String street;
    private String city;
    private String postalCode;
    private String state;
    private String country;

    public Address(String... params) {
        street = params[0];
        city = params[1];
        //等等。在调用构造函数时,请确保按照赋值顺序传递参数。还要首先检查 varargs 的大小,
        //以免分配不存在的参数。
    }
}

然后可以像这样调用它,仅设置街道和城市:

Address address = new Address("myStreet", "myCity");

另一种选择是使用一个带有所有参数的构造函数,如果你不想设置某个值,请在对应参数的位置传递 null 到构造函数中:

Address address = new Address("myStreet", "myCity", null, null, null);
英文:

You can do it with one constructor with varargs, since all fields of your class are of type String:

public class Address {
    private String street;
    private String city;
    private String postalCode;
    private String state;
    private String country;

    public Address(String... params) {
      street = params[0];
      city = params[1];
      //etc. Just take care to pass the arguments in the order you are 
      //assigning them when you call the constructor. Also check the size 
      //of varargs first so you don't assign arguments that don't exist.
    }

}

And then call it like so to set only the street and city:

Address adress = new Address("myStreet", "myCity");

An alternative is to have one constructor with all the arguments, and if you don't want to set a value, pass null to the constructor in place of the corresponding parameter:

Address adress = new Address("myStreet", "myCity", null, null, null);

huangapple
  • 本文由 发表于 2020年10月7日 05:02:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64233750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定