this关键字:
作用:出现在成员方法,构造器中代表当前对象的地址,用于访问对象的成员变量,成员方法
this出现在有参数构造器中的用法:
public class Car{
String name;
double price;
public Car(String name , double price){
this.name = name;
this.price =price;
}
}
this出现在成员方法中的用法:
public class Car{
String name;
double price;
public void gowith(String name ){
System.out.println(this.name + "正在和" + name);
}
}
this测试代码
public class TestThis {
int a,b,c;
TestThis(){
System.out.println("正要new一个Hello对象");
}
TestThis(int a,int b){
//Hello(); // //这样是无法调用构造方法的!
this(); //调用无参的构造方法,并且必须位于第一行!
a = a;//这里都是指的局部变量而不是成员变量
this.a = a;//这样就区分了成员变量和局部变量. 这种情况占了this使用情况的大多数!
this.b = b;
}
TestThis(int a,int b,int c){
this(a,b);
this.c = c;
//调用无参的构造方法,并且必须位于第一行!
}
void sing(){}
void chifan(){
this.sing(); //sing();
System.out.println("你妈妈喊你回家吃饭!");
}
public static void main(String[] args){
TestThis hi = new TestThis(2,3);
hi.chifan();
}
}
this关键字在构造器中成员方法中可以做什么?
可以用于访问当前的成员变量
this关键字
this的作用:this表示的是当前对象的本身,代表当前对象的一个引用,普通方法中,使用this:区分类成员属性和方法的形参,调用当前对象的其他方法 位置:任意
构造方法中使用this:使用this 来调用其他构造方法
位置:必须是第一条语句(第一行)
this不能用于static方法中
总结:
– This代表当前对象自身的引用(必须new)
– This可以修饰属性,区别成员变量和局部变量 – This修饰方法
– This修饰构造方法(必须是第一条语句)