1:this关键字是什么?
this 关键字是一个变量,可以在方法中使用,用来拿到当前对象,那个对象调用方法,this就指向哪个对象,也就是拿到哪个对象
2.this关键字在实际开发中常用来干什么?
用来解决对象的成员变量和方法内部变量的名称一样时,导致的访问冲突的问题。
eg:在Test中调用thiskey对象及其方法:
Test:
package Key; public class Test { public static void main(String[] args) { thiskey s=new thiskey(); System.out.println(s);//输出的s 在堆内存中创建的的keythis对象地址 s.PintThis();//调用方法时,先将自己在堆内存中创建的keythis对象地址传给方法中的this System.out.println("--------------------------------------"); thiskey s2=new thiskey(); System.out.println(s2); s2.PintThis(); s.PintThis(); //测试 thiskey test=new thiskey(); test.score=200;//访问当前thiskey对象前变量 test.printPass(300); } }
thiskey:
package Key; public class thiskey {//类 double score;//成员变量score public void PintThis() { //thiskey类中的方法 //注意不能是static //认识this:this是一个变量,可以用在方法中,来拿到当前对象 System.out.println(this); } public void printPass(double score){//此处score即this.score if(this.score>score){//注意score指的是从方法中的形参获得到的,而this.score指的是上面的成员变量score System.out.println("successful"); System.out.println(this.score); } else{ System.out.println("失败~"+this.score); } } }