21 对于对象中set方法的理解

        对于一个Student对象,属性有name和age,而age一般是比0大的,赋值不可能是负数,可以通过set方法来控制!Student对象如下:

public class Student {
    // 成员变量
    private int age;

    public Student() {
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age >0 && age <120){
            this.age = age;
        }else {
            System.out.println("您输入的年龄有误!");
        }

    }

}

        创建Student对象,输入负数的年龄,当年龄为负数时,只会打印出一个信息,不会对默认的年龄进行更改。

public class Demo1 {
    public static void main(String[] args) {
        Student student = new Student();
        student.setAge(-10);
        System.out.println("年龄:"+student.getAge());
    }
}

猜你喜欢

转载自blog.csdn.net/no996yes885/article/details/131872140
21
21)
今日推荐