java中类的属性私有化之后,初始化可以通过两种方式。
(1)设置setter方法
class="java" name="code">
public class TestDemo20 {
public static void main(String[] args){
Test20 test = new Test20();
test.setter(20);
System.out.println(test.getName());
//test.setter("zhangsan");
Test20 test1 = new Test20();
test1.setter(30,"lisi");
}
}
class Test20{
private int num;
private String name;
public void setter(int num){ //setter方法设置num属性
this.num = num;
}
public void setter(String name){//setter方法重载设置name属性
this.name = name;
}
public void setter(int num,String name){//setter方法重载同时设置num、name属性
this.num = num;
this.name = name;
}
public int getNum(){ //get方法取得num
return num;
}
public String getName(){ //get方法取得name
return name;
}
}
(2)通过
构造器初始化
public class TestDemo21 {
public static void main(String[] args){
Test21 test = new Test21();
}
}
class Test21{
private int num;
private String name;
public Test21(){} //Test21无参构造器
public Test21(int num,String name){ //Test21
this.num = num;
this.name = name;
}
public int getNum(){
return this.num;
}
public String getName(){
return this.name;
}
}
这两种方式都有什么优缺点呢?个人只是感觉使用构造器貌似是代码简化很多