this关键字:
- this是一个引用,是一个变量,this变量中保存了指向自身的内存地址,this存储在JVM堆内存
- 每一个Java对象都有一个this,各个不同
- this在多数情况下可以省略不写
- this不能使用在带static的方法中,如果想访问就在方法里new一个
package Test;
public class Constract {
public static void main(String []args) {
Account a=new Account();
a.setActon("1");
Account b=new Account();
b.setActon("2");
System.out.println(a.showActon());
System.out.println(b.showActon());
}
}
实例变量在堆内存的对象内部储存,所以访问该数据的时候,必须先创建对象,通过引用方式访问
不带static的方法被称为实例方法
不带static的变量被称为实例变量
实例方法的访问通过 引用.访问
当一个动作执行过程中需要对象参与,则一定要定义为实例方法,不带static关键字
package Test;
public class Account {
private String acton;
private double blance;
public Account() {
}
public void setActon(String a) {
this.acton=a;
}
public String showActon() {
return this.acton;
}
}
这里的acton是实例变量,也就是说通过对象引用访问的,所以可以不加this.
private int a=10;
public static void show() {
System.out.println(a);
}
static方法执行过程中没有当前对象,因为带有static的方法是通过类型名访问,或者说,这个上下文里没有当前对象,自然也不存在this。
static方法不能直接访问实例变量和实例方法。
public class Constract {
int i=10;
//static方法不能访问实例变量
public static void main(String []args) {
//不可以直接访问
System.out.println(i);
//实例变量通过引用来访问
Constract c=new Constract();
System.out.println(c.i);
}
}
this不可以省略的情况:用来区分局部变量和实例变量的时候
private int id;
public void seta(int id) {
this.id=id;
}
this用于调用构造方法
public class Constract {
int i=10;
//static方法不能访问实例变量
public static void main(String []args) {
Date d=new Date();
d.show();
Date d2=new Date(2019,4,7);
d2.show();
}
}
public class Date {
private int year;
private int month;
private int day;
Date(){
this(1970,1,1);
}
Date(int year,int month,int day){
this.year=year;
this.month=month;
this.day=day;
}
public void show() {
System.out.println(this.year+"年"+this.month+"月"+this.day+"日");
}
}