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的细致内容,更多请关注ki4网别的相干文章!