1.1、this是一个关键字,是一个引用,保存内存地址指向自身。每创建一个对象就有一个this。
1.2、this可以使用在实例方法中,也可以使用在构造方法中。
1.3、this出现在实例方法中其实代表的是当前对象。
1.4、this不能使用在静态方法中。
1.5、
1.6、this() 这种语法只能出现在构造方法第一行,表示当前构造方法调用本类其他的构造方法,目的是代码复用。
实例变量的访问一定要有对象。
主要是两个方法,一个加static的一个不加static的
例子:
//带有static的方法不能使用this
public static void dosum() {
CeShi w=new CeShi();
w.name="陈绪杰2";
System.out.println(w.name);
//System.out.println(this.name);错误
}
//不带有static的方法可以使用this
public void sohello() {
System.out.println(this.name);
}
三、调用实例方法:
调用实例方法一定要有对象的存在
带有static的方法不能直接访问实例变量和实例方法、
因为实例对象和实例方法都需要有对象的存在。
例子:
public class Test02 {
//实例变量
String name="陈绪杰2222";
//实例方法
public void dosum(){
System.out.println("陈绪杰");
System.out.println(name);
System.out.println(this.name);
}
public static void main(String[] args) {
//带有static的方法,不创建对象不能调用实例变量和实例方法
//创建变量
Test02 tt=new Test02();
System.out.println(tt.name);
tt.dosum();
}
}
四、this不能省的情况:
this. 大部分情况下可以省略,但是用来区分局部变量和实例变量的时候不能省略。
例子:
public class Test03 {
int id;
public void su(int a){
id=a;//因为实例对象有对象,所以这里的this可以省略
System.out.println(id);
}
public void su2(int id){
this.id=id;//这里的this就不可以省略,用于区分实例变量与局部变量
System.out.println(this.id);
}
public static void main(String[] args) {
//创建对象
Test03 tt=new Test03();
tt.su(20);
tt.su2(30);
}
}
写一个类步骤
1、私有化属性
2、创建get,set方法
3、构造无参的和有参的方
五、this的使用地方1、出现在实例方法当中,代表当前对象
格式: this.实例变量
2、出现在构造方法当中
this(实参列表) 这种语法只能出现在构造方法第一行,表示当前构造方法调用本类其他的构造方法,目的是代码复用。
例子:
//构造有参的方法
public This04(int no, String name) {
this.no = no;
this.name = name;
}
//构造无参的方法与上面的方法出现代码重复,所以使用下面的调用构造方法
public This04() {
//new This04(10,"chenxujie");//这种会在创建一个对象最终输出的值为空
this(10,"chenxujie");//正确的写法
}



