首页 > 解决方案 > 有人可以解释 makeDeepCopy 方法。静态部分是什么意思?

问题描述

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;
    }
}

标签: java

解决方案


它不与类同名,类名是Name,而方法名是makeDeepCopy。您看到的 Name 只是返回类型。

makeDeepCopy 正在摄取一个 Name 对象并创建一个具有相同值的新 Name 对象。它上面的 Name 构造函数(提取 Name 名称)由 makeDeepCopy 调用,并创建一个新的 Name 对象,该对象具有与传递给 makeDeepCopy 的 Name 对象相同的数据。


推荐阅读