this关键字
this存储在JVM堆内存中 在创建对象时候自动生成 用C1访问对象,整个过程中出现的this就是C1;C2同理;
·没有static关键字的方法称为“实例方法”,访问实例方法使用"引用.方法名";
·没有static关键字的变量称为“实例变量”。
注意:有对象参与的,即使用堆内存时,这个方法就一定没有static关键字;
在类的方法中, 若要调用自己类中的属性也需要引用,用this关键字;
(this代表当前正在执行行为的对象)
注意:含static的方法调用不需要对象,直接使用类名.方法名,所以执行过程中没有当前对象,所以this不能使用在含static的方法中。
this. 大多数可以省略,但用于区分局部变量和实例变量时不能省略
this用法
1.用在实例方法当中,代表当前对象【语法:this.】
2.用在构造方法中,通过当前的构造方法调用其他的构造方法【语法:this(实参);】this()语法只能出现在第一行代码中!
(即this只能调用一次)
用法案例:
package com.hdpowernode.javase.fengzhuang;
public class test {
//没有static的变量
int i =10;
//带有static的方法
public static void doSome(){
System.out.println("doSome!");
}
//没有static的方法
public void doOther(){
System.out.println("doOther!");
}
public static void method1(){
//调用doSome
//完整方法
test.doSome();
//省略方法
doSome();
//调用doOther
//完整方法
test test1 = new test();
test1.doOther();
//访问i
//完整方法
System.out.println(test1.i);
}
public void method2(){
//调用doSome
//完整方法
test.doSome();
//省略方法
doSome();
//调用doOther
//完整方法
test test1 = new test();
test1.doOther();
//省略方法
this.doOther();
//访问i
//完整方法
System.out.println(this.i);
//省略方法
System.out.println(i);//此处省略了 test.i
}
public static void main(String[] args) {
//要求在这里编写程序调用method1
//使用完整方式调用
test.method1();
//使用省略方式调用
method1();
//要求在这里编写程序调用method2
//使用完整方式调用
test me = new test();
me.method2();
}
}
带有static的方法,既可以采用类名.方法名的方式访问,也可以采用引用的方式访问。
但是即使采用引用的方式去访问,实际上执行时与引用指向的对象无关(所以不会出现空指针异常)。
在myeclipse中,使用引用的方式访问带有static的方法,程序会出现警告。