您好,欢迎访问一九零五行业门户网

java中什么是this

this关键字是什么?
关键字this只能在方法内部使用,表示对当前对象的引用。
this关键字的用法
1、访问成员变量,区分成员变量和局部变量
2、访问成员方法
3、访问构造方法
4、返回对当前对象的引用
5、将对当前对象的引用作为参数传递给其他方法
用法如下:test0505.java
class person{ private string name;//成员变量 private int age; person(){} person(string name){//局部变量 this.name=name;//1.用"this.成员变量名称"和重名的局部变量区分开来 } person(string name,int age){ this(name); this.age=age; } string getinfo(){//成员方法 return "姓名:" + name + "\n年龄:" + age; } void print(){ system.out.println(this.getinfo());//2.用"this.成员方法名"访问成员方法。 system.out.println(getinfo());//这种情况this关键字一般不写,让编译器自动添加。 }}public class test0505{ public static void main(string[] args){ person p=new person("张三",33); p.print(); }}
class person{ private string name; private int age; person(){} person(string name){//不含this()的构造方法 this.name=name; } person(string name,int age){//在构造方法内调用另一个构造方法 this(name);//3."this();"访问构造方法必须放在构造方法的第一行 this.age=age; } string getinfo(){ return "姓名:" + name + "\n年龄:" + age; } void print(){ system.out.println(this.getinfo()); }}public class test0505{ public static void main(string[] args){ person p=new person("张三",33); p.print(); }}
class leaf{ private int i=0; leaf increment(){ i++; return this;//4.返回对当前对象的引用。 } void print(){ system.out.println("i="+i); }}public class test0505{ public static void main(string[] args){ leaf x=new leaf(); x.increment().increment().increment().print(); }}
class person{ void eat(apple apple){ apple peeled=apple.getpeeled(); system.out.println(peeled); }}class apple{ apple getpeeled(){ system.out.println(this);//输出对当前对象的引用。 return peeler.peel(this);//5.将对当前对象的引用作为参数传递给其他方法。 }}class peeler{ static apple peel(apple apple){ return apple; }}public class test0505{ public static void main(string[] args){ apple a=new apple(); system.out.println(a); new person().eat(a); }}
推荐教程:java快速入门
以上就是java中什么是this的详细内容。
其它类似信息

推荐信息