例1


package fengzhuangxing;
/**1使用private关键字进行封装,修饰的所以数据只能在本类中访问
*2对外进行提供简单操作入口,
*3对外提高两方法 修改set,读取get
*set方法命名规范
* public void set+属性名首字母大写(形参){}
*
* public void setAge(int a){
* age=a;
* }
*get方法命名规范:
* public int getAge(){
* return age;
* }

setter 和 getter方法没有static关键字
static关键字修饰的方法调用:类名.方法名(实参)
没有static关键字修饰的方法调用:引用.方法名(实参)

*/
public class User {

private int age;
public void setAge(int a) {
//age=a;
if(a<0 || a>100) {
System.out.println("输入错误");
return;
}
age=a;
}
public int getAge() {
return age;
}
}

//测试
package fengzhuangxing;

public class UserTest {

public static void main(String[] args) {

User user=new User();
// System.out.println("该用户年龄:" + user.age);
// user.age=20;
// System.out.println("该用户年龄:" + user.age);
// user.age=-100;
// System.out.println("该用户年龄:" + user.age);
//
//修改
user.setAge(-100);
//读取
System.out.println(user.getAge());

}

例2


package fengzhuangxing;

public class Customer {

private int id;
private String name;
private int age;
//下面getter, settter可以直接生成,鼠标右键,Source--->Generate getters and setter即可
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//测试
package fengzhuangxing;

public class CustomerTest {

public static void main(String[] args) {

Customer c= new Customer();

c.setId(1222);
c.setName("张三");
c.setAge(45);

System.out.println(c.getId());
System.out.println(c.getName());
System.out.println(c.getAge());
}
}