Java 中的this关键字
原文: https://javabeginnerstutorial.com/core-java-tutorial/this-keyword-java/
this是什么
this是 Java 中的关键字。 可以在类的方法或构造器内部使用。 它(this) 用作对当前对象的引用,当前对象的方法或构造器正在被调用。 this关键字可用于从实例方法或构造器中引用当前对象的任何成员。
this关键字和字段(实例变量)
this关键字在处理变量隐藏时可能非常有用。 我们不能创建两个具有相同名称的实例/局部变量。 但是,创建一个实例变量&,一个具有相同名称的局部变量或方法参数是合法的。 在这种情况下,局部变量将隐藏实例变量,这称为变量隐藏。
变量隐藏示例
class JBT {int variable = 5;public static void main(String args[]) {JBT obj = new JBT();obj.method(20);obj.method();}void method(int variable) {variable = 10;System.out.println("Value of variable :" + variable);}void method() {int variable = 40;System.out.println("Value of variable :" + variable);}}
上面程序的输出
Value of variable :10Value of variable :40
如您在上面的示例中看到的那样,实例变量正在隐藏,并且局部变量(或“方法参数”)的值不显示为实例变量。 要解决此问题,请使用this关键字,并使用一个字段指向实例变量而不是局部变量。
this关键字用于变量隐藏的示例
class JBT {int variable = 5;public static void main(String args[]) {JBT obj = new JBT();obj.method(20);obj.method();}void method(int variable) {variable = 10;System.out.println("Value of Instance variable :" + this.variable);System.out.println("Value of Local variable :" + variable);}void method() {int variable = 40;System.out.println("Value of Instance variable :" + this.variable);System.out.println("Value of Local variable :" + variable);}}
上面程序的输出
Value of Instance variable :5Value of Local variable :10Value of Instance variable :5Value of Local variable :40
this关键字和构造器
this关键字可以在构造器内使用,以调用同一类中的另一个重载构造器。 这称为显式构造器调用。 如果一个类有两个重载的构造器,一个不带参数,另一个不带参数,则会发生这种情况。 然后this关键字可用于从构造器中调用带有参数的构造器,而无需使用参数。 这是必需的,因为无法显式调用构造器。
this与构造器的示例
class JBT {JBT() {this("JBT");System.out.println("Inside Constructor without parameter");}JBT(String str) {System.out.println("Inside Constructor with String parameter as " + str);}public static void main(String[] args) {JBT obj = new JBT();}}
The output of the above program
Inside Constructor with String parameter as JBTInside Constructor without parameter
如您所见,this可用于调用同一类中的重载构造器。
注意:
this关键字只能是构造器中的第一个语句。- 构造器可以具有
this或super关键字,但不能同时具有这两个关键字。
this关键字和方法
this关键字也可以在 Methods 内部使用,以从同一类调用另一个方法。
this关键字与方法的示例
class JBT {public static void main(String[] args) {JBT obj = new JBT();obj.methodTwo();}void methodOne(){System.out.println("Inside Method ONE");}void methodTwo(){System.out.println("Inside Method TWO");this.methodOne();// same as calling methodOne()}}
上面程序的输出
Inside Method TWOInside Method ONE
this关键字作为方法参数的示例
public class JBTThisAsParameter {public static void main(String[] args) {JBT1 obj = new JBT1();obj.i = 10;obj.method();}}class JBT1 extends JBTThisAsParameter {int i;void method() {method1(this);}void method1(JBT1 t) {System.out.println(t.i);}}
如果您正确理解了this关键字,那么下一步应该是从 Java 教程了解 Java 中的static关键字。
参考文献
1- 官方文档
