1. this与实例化对象的关系
this是Java虚拟机在创建对象时自动创建的指向该对象的指针
this用于方法中,而this指代的是该方法所属类的当前对象(当前实例化对象
输出对象地址与this地址
//输出对象地址与this地址
> public class ref_03 {
int number = 18;
public static void main(String[] args) {
ref_03 r3 = new ref_03();
ref_03 r2 = new ref_03();
r3.say(r2);//这里r3表示say()所属类的当前对象,即this指针指向的地址
}
public void say(ref_03 r5){
System.out.println(this);
System.out.println(r5);
}
}
2. 通过实例化对象实现在static方法中调用non-static方法or属性
在main方法中实例化了两种对象,通过这两个实例化的对象实现了在static main函数中调用非静态变量,方法同理
class ref_int{
int i = 20;
}
public class ref_03 {
int number = 18;
public static void main(String[] args) {
ref_int r1 = new ref_int();
ref_03 r3 = new ref_03();
ref_03 r2 = new ref_03();
r1.i = 30;
System.out.println(r1.i);
System.out.println(r2.number);
System.out.println(r3.say(r1,r2));//这里r3表示say()所属类的当前对象,即this指针指向的地址
}
public int tell(ref_int r2){
r2.i = 40;
this.number = 200;
return r2.i;
}
3. 为什么在main函数中实例化对象后仍然无法用this引用non-static属性,方法
main函数中的this属于main函数,而main属于类本身,而不是已经实例化的对象,所以实例化的对象与this无关,尽管main函数被包含在该对象中.
类中方法其实分为两种;一种是实例所属的方法,一种是类本身拥有的方法,从调用方法的方式上可以看出这点.
People.name();//静态方法从属于类本身
Juddy.name();//非静态方法从属于对象
撒由那拉,下次见.