this keyword in java
1. this keyword is used to hold address of current instance.
public class Test {
void showCurrentAddress() {
System.out.println(this);
}
public static void main(String[] args) {
Test t1=new Test();
t1.showCurrentAddress();
System.out.println(t1);
Test t2=new Test();
t2.showCurrentAddress();
System.out.println(t2);
}
}
Output is :
Test@5e265ba4 Test@5e265ba4 Test@36aa7bc2 Test@36aa7bc2
2. this keyword is ude to remove confliction between local variable and instance variable.
public class Test {
String name = "Deep Singh";
void showCurrentAddress(String name) {
System.out.println(name);
System.out.println(this.name);
}
public static void main(String[] args) {
Test t1 = new Test();
t1.showCurrentAddress("nikku");
}
}
Output is :
nikku Deep Singh
3. this keyword is used to achieve method chaining by returning this keyword.
public class Test {
Test a() {
System.out.println("a");
return this;
}
Test b() {
System.out.println("b");
return this;
}
Test c() {
System.out.println("c");
return this;
}
public static void main(String[] args) {
new Test().a().b().c();
}
}
Output is :
a b c
4. this keyword is used to pass as an argument.
class Friend {
void access(Test t) {
System.out.println(t.roll);
System.out.println(t.name);
}
}
public class Test {
String name;
int roll;
void share() {
new Friend().access(this);
}
public static void main(String[] args) {
Test t = new Test();
t.name = "Deep Singh";
t.roll = 123;
t.share();
}
}
Output is :
123 Deep Singh
Note: this keyword can never used inside static context.
this() Constructor in Java
this() is used to call current class constructors or local constructors chaining.
public class Testing {
public Testing() {
this(10);
System.out.println("default constructor");
}
public Testing(int i) {
this("hello");
System.out.println("int constructor");
}
public Testing(String name) {
System.out.println("string constructor");
}
public static void main(String[] args) {
new Testing();
}
}
Output is :
string constructor int constructor default constructor
Note : this() constructor must be used inside a constructor and that must be the first statement.
No comments:
Post a Comment