Рет қаралды 26
this is a reference variable that refers to the current object
The main purpose of using ‘this’ keyword is to differentiate the local variable and data members of class whenever the data members of the class and the local variables have the same names without creating the ambiguity to JVM
Public class Rectangle{
int length, width;
Rectangle (int length, int width)
{
this.length = length;
this.width = width;
}
It can be used to call one constructor within the other constructor without creating the objects multiple tome for the same class.
This helps to avoid code duplication
class Student {
int age;
Student ( )
{
this(20);
}
Student ( int age )
{
this.age =age;
}
public static void main(String args[]) {
Student ss= new Student( );
Student s = new Student(23);
System.out.println(s.age);
System.out.println(ss.age);
}
}
Output: - 23
20