引入
1 2 3 4 5 6 7 8 9 10 11
| class Dogt{ public String name public int age; public Dog(String dName,int dAge){ name = dName; age = dAge; } public void info(){ System.out.println(name + "/t" + age + "/t"); } }
|
问题:构造方法的输入参数名不是非常的好,如果能够将dName改成name就好了,但是我们会发现按照变量的作用域原则,name的值就是nul,怎么解决->this
1 2 3 4 5 6 7 8 9 10 11 12
| class Dog { public string name; public int age; public Dog(String name,int in_aget){ this.name = name; this.age=in_age; } public void info(){ System.out.println(this.name + "t" + this.age + "t" + "当前对象的hashCode是:" + this.hashCode()); } }
|
小结 :简单来说,对哪个对象调用,this就代表哪个对象
this的注意事项和使用细节
- this 关键字可以用来访问本类的属性、方法、构造器
- this 用于区分当前类的属性和局部变量
- 访问成员方法的语法:this.方法名(参数列表);
- 访问构造器语法:this(参数列表); 注意只能在构造器中使用(即只能在构造器中访问另外一个构造器, 必须放在第一条语句)
- this 不能在类定义的外部使用,只能在类定义的方法中使用。