java三个功能:封装 继承 多态
封装的目的:隐藏对象属性(int age)和实现细节,对外提供访问方式(接口)//setxxx.getxxx.方法
人
{
属性:年龄
行为:说话
}
class Person{
private int age;
public void setAge(int a) {//方法可以加入语句进行判断
if (a<0||a>130) {
// System.out.println("输入的"+age+"有误");
throw new RuntimeException("输入的"+age+"有误");//抛出异常
}
else {
this.age=a;
}
}
public int getAge() {
return age;
}
void speak() {
System.out.println("age="+age);}
}
public class PersonDemo {
public static void main(String []args) {
Person p = new Person();
/*p.age=20;
p.speak();*/
p.setAge(20);
p.speak();
}
}