public和private修饰符&&set and get 方法,类内部访问控制实现机制。example:
section:code
public class Person {
public static void main(String[] args) {
PersonTwo ming=new PersonTwo();
ming.setName("小李");
String name=ming.getName();
System.out.println(name);
ming.setAge(156);
int age=ming.getAge();
System.out.println(age);
}
}
class PersonTwo {
private String name;
private int age;
//set和get方法
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}
//age
public void setAge(int age) {
//检测输入的age是否合法
if(age<18||age>99) {
System.out.println("age参数不合法!");
}else {
this.age=age;
}
}
public int getAge() {
return age;
}
}