Java,封装代码

来源:互联网 发布:sftp默认端口号 编辑:程序博客网 时间:2024/06/06 16:48
package com.xiaobudiao.oop;
//权限修饰符:public private protected 缺省 
public class TestAnimal {
public static void main(String[] args) {
Animal a1 = new Animal();
// a1.name="花花";
//  a1.legs=4;
a1.setLegs(4);
a1.setName("huahua");
a1.info();
a1.eat();
}
}
class Animal{
//private修饰的属性,只能在本类中调用;
//出了此类,就不能被调用了
private String name;//动物的名字
private int legs;//几条腿
public void eat(){
System.out.println("动物吃食");
}
public void sleep(){
System.out.println("动物休眠");
}
public void info(){
System.out.println("name:"+name+",legs:"+legs);
}
//设置类的属性
public void setLegs(int l){
if(l>0 && l%2==0){
legs=l;
}else{
System.out.println("你输入的数据有误");
}
}
public void setName(String n){


name = n;
}
//获取类的属性
public int getLegs(){
return legs;
}
public String getName(){
return name;
}


}