Java中的this关键字和this()方法

Java'this'关键字

  • 这是Java中引入的关键字。

  • 如果方法或构造函数的实例变量名称与本地变量名称相同,则可以使用此关键字访问实例变量。

示例

class ThisInstanceVariable{
	String str;
	
	ThisInstanceVariable(String str){
		this.str = str;
	}

	public void print(){
		System.out.println(str);
	}
	
	public static void main(String[] args){
		ThisInstanceVariable tiv = new ThisInstanceVariable("My Name Is Preeti jain");
		tiv.print();
	}
}

输出结果

D:\Java Articles>java ThisInstanceVariable
My Name Is Preeti jain
  • 如果实例变量的名称与方法的局部变量相同,则此关键字可解决歧义问题。

  • 此关键字可以作为方法调用中的参数传递。它表示传递当前对象。

  • 如果我们正在调用同一类的其他构造函数,则此关键字可以在构造函数调用中作为参数传递。

  • 此关键字可用于调用当前的类方法。

示例

class MethodCallByThis{

	MethodCallByThis(){
		this.print();
	}

	public void print(){
		System.out.println("Welcome in the print method");
	}
	
	public static void main(String[] args){
		MethodCallByThis mcbt = new MethodCallByThis();
	}
}

输出结果

D:\Java Articles>java MethodCallByThis
Welcome in the print method

Java'this()'方法

  • java中引入的this()方法。

  • this()方法可用于调用当前类的另一个构造函数。

示例

class ConstructorCallByThis{
	String str;

	ConstructorCallByThis(){
		this("calling string constructor");
	}
	
	ConstructorCallByThis(String s){
		System.out.println("Welcome in string constructor");
	}
	
	public static void main(String[] args){
		ConstructorCallByThis ccbt = new ConstructorCallByThis();
	}
}

输出结果

D:\Java Articles>java ConstructorCallByThis
Welcome in string constructor