JAVA-private关键字

image

package com.itheima;
/*
学生类
 */

public class student01 {

    //成员变量
    private String name;//给name设置private
    private int age;

    public void setAge(int a) {//设置set方法 给age赋值
        age=a;
//        if(a<=0 || a>=120){
//            System.out.println("你输入的年龄有误");
//        }else {
//            age=a;
//        }
    }


    public int getAge() {//用get方法返回age的值
        return age;
    }

    public void setName(String n) {
        name = n;
    }

    public String getName() {
        return name;
    }
}
package com.itheima;
/*
学生测试类
 */

public class StudentDemo01 {
    public static void main(String[] args) {
        // 创建对象
        student01 s = new student01();


        //给成员变量复制
        s.setName("林青霞");//赋值给name
        s.setAge(30);//赋值给age
        System.out.println(s.getName()+","+s.getAge());//调用get方法获取name和age的值

    }
}

执行结果

林青霞,30

Process finished with exit code 0
posted @ 2022-11-09 23:06  NiceTwocu  阅读(14)  评论(0编辑  收藏  举报