JAVA-this关键字

image


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

public class student02 {

    //成员变量
    private String name;
    private int age;

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


    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }//this关键字加上就代表的是成员变量,因为方法里的形参与成员变量名称相同

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

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


        //给成员变量复制
        s.setName("林青霞");
        s.setAge(30);
        System.out.println(s.getName()+","+s.getAge());

    }
}

执行结果

林青霞,30

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