this:哪个对象调用方法,this就代表哪个对象
案例1:
//定义老师类 class Teacher { private String name; private int age; public String getName(){ return name; //return this.name;这里隐含了this, //因为局部没有name变量,所以不需要写this } public int getAge(){ return age; } public void setName(String name){ this.name = name; } public void setAge(int age){ this.age = age; } } class Test{ public static void main(String[] args){ Teacher t = new Teacher(); t.setName("张三"); t.setAge(23); System.out.println(t.getName() + "---" + t.getAge()); Teacher t2 = new Teacher(); t2.setName("李四"); t2.setAge(30); System.out.println(t2.getName() + "---" + t2.getAge()); } }
输出:
张三---23 李四---30
时间: 2024-10-05 22:58:11