this关键字
当成员变量和局部变量重名时,在方法中使用this时,表示的是该方法所在类中的成员变量。(this是当前对象自己)
public class test { String s="5555"; public test(String s){ System.out.println(this.s); this.s=s; } public static void main(String[] args) { System.out.println("this关键字调用,该变s的变量"); test t=new test("6666"); System.out.println(t.s); } }
用this关键字判断2个人是否同龄
public class test { public static void main(String[] args) { person p1=new person(10); person p2=new person(20); p1.compare(p2); } } class person{ int age; public person(int age){ this.age=age; } public boolean compare(person p){ if(this.age==p.age){ System.out.println("同龄"); return true; }else{ System.out.println("不同龄"); return false; } } }

浙公网安备 33010602011771号