Reference type variable "this"
It indicates instance itself.
can use in instance method and constructor! (CANNOT use in static method(class method))
To distinguish local variable and instance variable
class Car {
//instance variable
String color;
String gearType;
int door;
Car(String color, String gearType, int door) {
//instance variable this.____
//this.color <=> Car.color
this.color = color;
this.gearType = gearType;
this.door = door;
}
}
example :
class MyMath2 {
//instance variable
long a,b;//this.a, this.b
//can use instance method and constructor only!
MyMath2(int a, int b) {//constructor
//distinguish iv(instance variable) and lv(local variable)
this.a = a;
this.b = b;
}
MyMath2() {
return a+b;//return this.a + this.b;
}
//static method(class method)
//without creating object.
//CANNOT use iv.
//CANNOT use this which indicate object itself!
static MyMath2(long a, long b) {//local variable
return a+b;
}
}
Last updated
Was this helpful?