java - 有人可以解释 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;
}
}
解决方案
它不与类同名,类名是Name,而方法名是makeDeepCopy。您看到的 Name 只是返回类型。
makeDeepCopy 正在摄取一个 Name 对象并创建一个具有相同值的新 Name 对象。它上面的 Name 构造函数(提取 Name 名称)由 makeDeepCopy 调用,并创建一个新的 Name 对象,该对象具有与传递给 makeDeepCopy 的 Name 对象相同的数据。
推荐阅读
- c++ - 在列中打印数字时如何避免打印垃圾?
- java - Ebean 中持续存在多级级联
- java - 如何在Java中修复对象不移出框架?
- r - 计算 2(为 2 定义一个函数,其中模型是一条线)
- c# - Autofac 使用接口自动进行程序集扫描 - .net core 3.0 - 根据 Lifetime 注册
- jquery - 鼠标悬停后无法删除悬停
- regex - Python 正则表达式多行
- javascript - JavaScript EventListener 未将事件变量传递给事件处理程序
- go - 在 Cloud Build 期间将存储库名称传递给 Slack 机器人
- python - QT QOpenGLWidget 大小错误