直接以代码解释:
class Man { private int age; private String name; Man() { name= null;age = 0; } Man(String n)//正常直接打印"BLF,0",但是把n改为name呢,就会打印null,0 { name = n; }//改成name虽然增加了阅读性,但是参数名进栈时,栈区已经有了一个局部变量名name, 那么name的赋值,只会把自己赋值给自己。如同int x = 5; x = x; /* Man(String name) { this.name = name;//this关键字的作用就是说,这个对象的name,那么会进堆内存,就不会起冲突了 } */ Man(int a) { age = a; } Man(int a,String n) { age = a; name = n; } void run() { System.out.println(name+","+age);//实际上这里省略了this.name+","+this.age } } public class Main { public static void main (String[] args) { Man jo = new Man("BLF"); jo.run(); } }所以:当局部变量和成员变量重名时,可以用关键字this来区分,this就代表当前对象(this就是所在函数所属对象的引用):
class Man { private int age; private String name; Man() { name= null;age = 0; } Man(String name) { this.name = name; } Man(int age) { this.age = age; } Man(int age,String name) { this.age = age; this.name = name; } void run() { System.out.println(this.name+","+this.age); } } public class Main { public static void main (String[] args) { Man jo = new Man("BLF"); jo.run(); } }
this 使用二:
this可以在构造函数里调用其他构造函数
错误演示:
class Man { private int age; private String name; Man() { name= null; age = 0; } Man(String name) { this.name = name; } Man(int age) { this.age = age; } Man(int age,String name) { //上面已经写过了,是不是就可以进行调用了呢?答案是否定的 this.Man(name);//this代表了对象,对象要想进行是使用必须先初始化,但是 this.Man(age);//这里还没有进行初始化,就开始使用,所以是错误的 } void run() { System.out.println(this.name+","+this.age); } } public class Main { public static void main (String[] args) { Man jo = new Man(12,"BLF");//此处传2个参数 jo.run(); } }修改
class Man { private int age; private String name; Man() { name= null; age = 0; } Man(String name) { this.name = name; } Man(int age) { this.age = age; } Man(int age,String name) { this(name);//调用上述构造函数,注意:必须放第一行,房子this.age = age;下面就错,理由见下 this.age = age; } void run() { System.out.println(this.name+","+this.age); } } public class Main { public static void main (String[] args) { Man jo = new Man(12,"BLF"); jo.run(); } }注意:this 规则:this只能定义在构造函数的第一行,因为初始化必须先执行
Man(int age,String name) { this.name = name;//初始化BLF this.age = age;//初始化12 this("gggg"); //改变BLF,变为gggg,故错误 }PS:this() 不要滥调用.
import java.security.cert.TrustAnchor; class Man { private int age; private String name; Man() { name= null; age = 0; } Man(String name) { this.name = name; } Man(int age) { this.age = age; } Man(int age,String name) { this(name);//调用上述构造函数,注意:见下 this.age = age; } public void run() { System.out.println(this.name+","+this.age); } /*判断两个人是否是同龄人*/ public boolean judge(Man g) { return this.age == g.age;//这里的this代表jo2 } } public class Main { public static void main (String[] args) { Man jo = new Man(12,"BLF"); Man jo2 = new Man(12,"BLF2"); boolean flag = jo2.judge(jo); if(flag==true) System.out.println("YES"); else System.out.println("NO"); } }