一.关于java中的this关键字
1.this代表当前对象
2.this不能用在static当中,static代表是类,this代表的是对象,有类不一定有对象
3.this能调用static修饰的方法和变量,类的东西被对象共享
this的用法:
1.this.属性名:在方法中局部变量名和成员(全局)变量名相同时。我们用this来区分全局变量和局部变量,this调用的一定是属于对象能第哦啊用的变量是全局变量
2.this.方法名:代表当前正在运行的对象调用该方法
3.this():不能在普通方法中使用,只能在构造器当中,还必须是第一条语句,调用的是一个构造器,
只要在this的()中赋值就行
在一个类下两个构造方法不能通过this()相互调用
不能与super()同时使用
二.从内存图中来认识this关键字(重点)
这里用people1访问该对象的时候this指针就是people1,用people2访问对象的时候this指针就是people2;
三.this指针的具体应用示例
class Test{
int age;
char sex;
String name;
public Test(){
/*
this.age = 1970;
this.sex = '男';
this.name = "GYX";
*/
this(20, '男', "GYX");
}
public Test(int age, char sex){
this.age = age;
this.sex = sex;
}
public Test(int age, char sex, String name){
this.age = age;
this.sex = sex;
this.name = name;
}
void MytoString(){
System.out.println("年龄:" + this.age + " 性别:" + this.sex + " 名字:" + this.name);
}
}
public class Test1 {
public static void main(String[] args) {
Test test = new Test();
test.MytoString();
Test test2 = new Test(18, '女', "郭");
test2.MytoString();
}
}
输出结果:
年龄:20 性别:男 名字:GYX
年龄:18 性别:女 名字:郭