The 'this
'
keyword is a reference variable that refers to the current object. It can be used to refer to the instance variables of the current object, invoke the current object's methods, and differentiate instance variables from local variables when they have the same name.
Here are some key uses of the this
keyword in Java:
- To refer to instance variables:
When there is a need to differ between instance variables and local variables with the same name, you can use '
this
'
to refer to the instance variables.public class MyClass {
private int x;
public void setX(int x) {
// Use "this" to refer to the instance variable
this.x = x;
}
}
- To invoke the current object's method:
this
'
to invoke the current object's method. This is often seen in constructors to call another constructor of the same class.public class MyClass {
private int x;
public MyClass() {
// Call the parameterized constructor using "this"
this(0);
}
public MyClass(int x) {
this.x = x;
}
}
- To pass the current object as a parameter to other methods:
When you need to pass the current object as a parameter to other methods, you can use '
this
'
.
public class MyClass {
private int x;
public void myMethod() {
// Pass the current object as a parameter
anotherMethod(this);
}
public void anotherMethod(MyClass obj) {
// Do something with the passed object
}
}
- In constructors to call another constructor:
()
is used to invoke another constructor from the same class.public class MyClass {
private int x;
public MyClass() {
// Call another constructor with a parameter
this(0);
}
public MyClass(int x) {
this.x = x;
}
}
Комментариев нет:
Отправить комментарий