java中的复制构造函数

java中的复制构造函数,java,copy-constructor,optional-parameters,Java,Copy Constructor,Optional Parameters,如果我以后想用这个怎么办: class Client{ private String name; private int age; private int amount; public Client(Client otherClient){ name=otherClient.name; age=otherClient.age; amount=otherClient.amount; } } 或 或 如何获得可选参数?我必须为每种情况定义构造函数吗? 谢谢是的,您必

如果我以后想用这个怎么办:

class Client{
private String name;
private int age;
private int amount;
public Client(Client otherClient){
    name=otherClient.name;
    age=otherClient.age;
    amount=otherClient.amount;
    }
}

如何获得可选参数?我必须为每种情况定义构造函数吗?
谢谢

是的,您必须
重载
构造函数,这是您应该仔细阅读的内容。它允许您为一个方法提供多个输入参数。调用该方法时,编译器将选择适当的方法


下面是关于重载的Javadocs:

是的,您必须
重载构造函数,这是您应该仔细阅读的内容。它允许您为一个方法提供多个输入参数。调用该方法时,编译器将选择适当的方法


下面是关于重载的Javadocs:

第一个答案绝对正确,但是如果您真的希望所有这些情况下只有一个构造函数,您可以编写如下内容:

Client c1=new Client("Smith",20,100);
用法:

public Client(String name, Integer age, Integer amount) {
    this.name = name;

    if (age != null) {
        this.age = age;
    }

    if (amount != null) {
        this.amount = amount;
    }
}
请注意,我在构造函数参数中使用了包装类
Integer
而不是
int
,因为
int
类型的变量不能为
null


另外,如果让setter返回this
,则将模拟Java中的命名参数:

Client c1 = new Client("Smith", null, null);
Client c2 = new Client("Smith", 20, null);
Client c3 = new Client("Smith", null, 100);
Client c4 = new Client(null, 20, 100);
Client c5 = new Client("Smith", 20, 100);

第一个答案绝对正确,但如果您真的希望所有这些情况下只有一个构造函数,您可以编写如下内容:

Client c1=new Client("Smith",20,100);
用法:

public Client(String name, Integer age, Integer amount) {
    this.name = name;

    if (age != null) {
        this.age = age;
    }

    if (amount != null) {
        this.amount = amount;
    }
}
请注意,我在构造函数参数中使用了包装类
Integer
而不是
int
,因为
int
类型的变量不能为
null


另外,如果让setter返回this,则将模拟Java中的命名参数:

Client c1 = new Client("Smith", null, null);
Client c2 = new Client("Smith", 20, null);
Client c3 = new Client("Smith", null, 100);
Client c4 = new Client(null, 20, 100);
Client c5 = new Client("Smith", 20, 100);

Java没有可选参数,您必须用适当的参数定义每个构造函数。Java没有可选参数,您必须用适当的参数定义每个构造函数。@user1347096没问题。如果您没有其他问题,可以单击“我的分数”下的复选标记,将此答案标记为已接受。或者你可以问上面更多的问题。Thanks@user1347096没问题。如果您没有其他问题,可以单击“我的分数”下的复选标记,将此答案标记为已接受。或者你可以问上面更多的问题。谢谢