成员变量私有化,一是为了体现面向对象的一种思想,即封装,二是向外界提供一种更加安全的访问方式,示例演示:测试类:
public class StudenTest {
public static void main(String[] args) {
Student s = new Student();
s.setName("小明");
s.setAge(14);
System.out.println(s.getName()+"*****"+s.getAge());
}
}
打印结果:
小明*****14
学生类:
public class Student {
//私有成员name
private String name;
//私有成员age
private int age;
//构造方法
public Student() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public void setAge(int age) {
this.age = age;
}
}
|