欧美亚洲中文,在线国自产视频,欧洲一区在线观看视频,亚洲综合中文字幕在线观看

      1. <dfn id="rfwes"></dfn>
          <object id="rfwes"></object>
        1. 站長資訊網(wǎng)
          最全最豐富的資訊網(wǎng)站

          java中什么是this

          java中什么是this

          this關(guān)鍵字是什么?

          關(guān)鍵字this只能在方法內(nèi)部使用,表示對當(dāng)前對象的引用。

          this關(guān)鍵字的用法

          1、訪問成員變量,區(qū)分成員變量和局部變量

          2、訪問成員方法

          3、訪問構(gòu)造方法

          4、返回對當(dāng)前對象的引用

          5、將對當(dāng)前對象的引用作為參數(shù)傳遞給其他方法

          用法如下:Test0505.java

          class Person{ 	private String name;//成員變量 	private int age; 	Person(){} 	Person(String name){//局部變量 		this.name=name;//1.用"this.成員變量名稱"和重名的局部變量區(qū)分開來 	} 	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關(guān)鍵字一般不寫,讓編譯器自動添加。 	} } 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()的構(gòu)造方法 		this.name=name; 	} 	Person(String name,int age){//在構(gòu)造方法內(nèi)調(diào)用另一個構(gòu)造方法 		this(name);//3."this();"訪問構(gòu)造方法必須放在構(gòu)造方法的第一行 		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.返回對當(dāng)前對象的引用。 	} 	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);//輸出對當(dāng)前對象的引用。 		return Peeler.peel(this);//5.將對當(dāng)前對象的引用作為參數(shù)傳遞給其他方法。 	} } 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快速入門

          贊(0)
          分享到: 更多 (0)
          網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號