本帖最后由 zhangx 于 2013-4-16 14:48 编辑
都说private是私有属性有保护机制,但是这两个代码都显示的是“帅哥王五的性别是怪物”,这怎么保护啊?
代码一(public):
class PublicDemo {
public String name;
public String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
if("男".equals(sex) || "女".equals(sex)){
this.sex = sex;
}else{
this.sex = "怪物";
}
}
}
public class PublicTest {
public static void main(String[] args) {
PublicDemo demo = new PublicDemo();
demo.setName("王五");
demo.setSex("不男不女");
System.out.println("帅哥"+demo.getName()+"的性别是"+demo.getSex());
}
}
代码二(private):
class PublicDemo {
private String name;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
if("男".equals(sex) || "女".equals(sex)){
this.sex = sex;
}else{
this.sex = "怪物";
}
}
}
public class PublicTest {
public static void main(String[] args) {
PublicDemo demo = new PublicDemo();
demo.setName("王五");
demo.setSex("不男不女");
System.out.println("帅哥"+demo.getName()+"的性别是"+demo.getSex());
}
} |