Java中this关键字概述

this关键字

  • 在类的方法定义中使用的this关键字代表使用该方法对象的引用
  • 当必须指出当前使用方法的对象是谁时要使用this
  • 有时使用this可以处理方法中成员变量参数重名的情况
  • this可以看作是一个变量,它的值是当前对象的引用
public class Leaf{
	int i=0;
	Leaf(int i) {this.i=i;} //this.i指Leaf类中的成员变量i,i指形参i
	Leaf increament(){
		i++;
		retutrn this; //此处this指向自身,return一个自身的对象,也就是返回一个Leaf类型的对象的引用
	}
	void print(){System.out.println("i="+i);}
	public static void main(String[] args){
		Leaf leaf = new Leaf(100); //实例化一个leaf对象
		Leaf.increament().increament.print(); //打印出102
		 
	}
	}

猜你喜欢

转载自blog.csdn.net/ruanwei_0317/article/details/81135735