关于java中的set方法以及get方法

来源:互联网 发布:ioscydia软件源闪退 编辑:程序博客网 时间:2024/06/06 20:32

*java语言的是一中面向对象的语言
所以在大多数的类中属性都是私有化,我们就需要通过set和get方法来调取;*
public class Person1 {

private String name;//设置私有化的属性private int age;//设置私有化的属性//设置set方法来设置name的值;public void setName(String name){    if(name.length()>6|| name.length()<2){        System.out.println("您输入的名字不符合规则");                return;            }    else {        this.name=name;    }}//通过get方法来使对象获得方法    public String getName(){        return this.name;    }    public void setAge(int age){        if(age>100||age<0){            System.out.println("您输入的年龄不合法");        }        else {            this.age=age;        }    }    public int getAge(){        return this.age;    }}

public class PersonTest1 {
public static void main(String[]args){

    Person1  P=new Person1();    p.age=100;//会提示错误,因为age属性为private;    //p.setAge(1000);    System.out.println("未能设置age的Field时:"+P.getAge());    P.setAge(30);    System.out.println("成功设置ageFile"+P.getAge());    P.setName("李刚");    System.out.println(P.getName());}

}

0 0
原创粉丝点击