【发布时间】:2019-06-29 21:06:13
【问题描述】:
makeDeepCopy 方法是什么意思? 它也是构造函数吗?以及为什么数据类型与类名相同。 我假设任何与类同名的方法都是构造函数?
public class Name {
// private instance => visible in Name class only!
private String firstName;
private String lastName;
// constructor
public Name(String firstName, String lastName) {
// this keyWord differentiates instance variable from local variable
// refers to the current object
this.firstName = firstName;
this.lastName = lastName;
}
public Name(Name name) {
// Copy constructor
this.firstName = name.getFirstName();
this.lastName = name.getLastName();
}
public static Name makeDeepCopy(Name name) {
// copy method
return new Name(name);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String toString() {
return this.firstName + " " + this.lastName;
}
}
【问题讨论】:
-
不,它不是构造函数,但它确实调用了构造函数。它创建一个新对象,其信息与传入的对象相同。
-
static只是意味着您不需要对象的实例来调用该方法 - 如果在这里需要它是有争议的,但是由于您有复制构造函数,所以它是一回事 -
所以它只是一个普通的方法?你会怎么称呼它?对象方法,因为它接受一个对象
-
它被称为静态工厂方法,在这种情况下,它可能被使用,因此方法名称可以传达有关其作用的额外信息。参见例如stackoverflow.com/a/929193/2891664
标签: java