Java Setter和Constructor的困惑 [英] Java Setter and Constructor confusion
问题描述
我对如何在Java中使用构造函数和设置器感到困惑,请参阅下面的示例代码:
I am a bit confused about how to use constructor and setter in Java, please see the sample code below:
public class Name {
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
public static void main(String[] args) {
Name a=new Name();
a.setName("123");
System.out.println(a.getName());
}
它打印出123,它使用的是setter方法而没有构造函数,我也写道下面的其他代码:
It prints out 123, it is using setter method without constructor, I also wrote the other code below:
public class Name {
private String name;
public Name(String nm){
name=nm;
}
public String getName(){
return name;
}
}
public static void main(String[] args) {
Name a=new Name("123");
System.out.println(a.getName());
}
这也打印出了123,它使用的是构造函数没有setter方法,这就是为什么我不明白构造函数和setter之间使用的区别是什么,请告诉我,加油!!
This one prints out 123 as well, it is using constructor without setter method, this is why I do not understand what the difference in using between constructor and setter, please advise, cheers!
推荐答案
如果要更改实例的 name
值,该怎么办。当然,您不会为此使用构造函数,因为它将创建一个新实例。在这种情况下,您将使用 setter
。
What if you want to change the value of name
for an instance. Of course, you wouldn't use constructor for that, as it will create a new instance. You would use a setter
in that case.
当然,如果要编写不可变类,那么您将不会提供任何设置者
。实例字段中的任何修改都会创建一个新实例。
Of course, if you are writing an immutable class, then you wouldn't give any setters
. Any modification in the instance fields, will create a new instance.
这里要了解的另一个重要点是,由于您在第二代码中提供了参数化构造函数,因此编译器不会添加任何默认构造函数。因此,第二类实际上没有任何0-arg构造函数。如果要稍后使用,则必须显式添加一个。
One more important point to understand here is, since you have provided a parameterized constructor in your 2nd code, the compiler wouldn't add any default constructor. So, the 2nd class doesn't actually have any 0-arg constructor. If you want to use it later on, then you have to add one explicitly.
这篇关于Java Setter和Constructor的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!