java类的封装范例2

2019年2月15日22:21:03 发表评论 977 views

本范例解决类的私有属性和外部设置属性的矛盾问题:

/**
 * Created by xabcd on 2019/2/15.
 */
public class Person
{
    private String name;
    private int age;
    void talk()//若将talk设置为私有方法,则在下面的程序中则无法访问
    {
        System.out.println("我是:"+name+",今年:"+age+"岁");
    }
    public void setName(String str){
        name= str;
    }
    public void setAge(int a){
        if(a>0)
            age = a;
    }
    public String getName(){
        return name;
    }
    public int getAge(){
        return age;
    }
}






/**
 * Created by xabcd on 2019/2/15.
 */
public class testPersonDemo2
{
    public static void main(String args[]) {
        //声明并实例化一个对象
        Person p = new Person();
        //给p中的属性赋值
        p.setName( "张三");
        p.setAge(25);
        //调用Person类中的talk()方法
        p.talk();
    }

}






结果:
我是:张三,今年:25岁

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: