java封装的妙处!
-------不封装
class Person01{
String name;
int age;
public void speak(){
System.out.println("我叫"+name+",今年"+age+"岁了");
}
}
public class TestFengzhuang01 {
public static void main(String[] args){
Person01 p = new Person01();
p.name ="小渣";
p.age = -18;//不符合实际情况
p.speak();
}
}
------封装
class Person02{
private String name;
private int age;
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age<=0||age>120)
System.out.println ("您输入的年龄不正确!");
else
this.age = age;
}
public void speak(){
System.out.println("我叫"+name+",今年"+age+"岁了");
}
}
public class TestFengzhuang02 {
public static void main(String[] args){
Person02 p = new Person02();
p.setAge(-18);
p.setName("小渣");
p.speak();
}
}