In Java, the this keyword is used to refer to the current object instance within a class, and can be used to access instance variables and methods.
Here's an example:
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; // Assigns the name parameter to the name instance variable this.age = age; // Assigns the age parameter to the age instance variable } public void printInfo() { System.out.println("Name: " + this.name); // Accesses the name instance variable using this keyword System.out.println("Age: " + this.age); // Accesses the age instance variable using this keyword } public static void main(String[] args) { Person myPerson = new Person("John", 30); myPerson.printInfo(); // Outputs "Name: John" and "Age: 30" } }
In this example, the Person class has two private instance variables, name and age, and a constructor that takes a name parameter and an age parameter. The this keyword is used to refer to the current object instance within the constructor, and is used to assign the parameter values to the instance variables. The printInfo() method also uses the this keyword to access the instance variables and output the person's name and age.
When an instance of the Person class is created and the printInfo() method is called, the person's name and age are output to the console.
The this keyword can also be used to call a constructor from within another constructor in the same class.
Here's an example:
public class Rectangle { private int length; private int width; public Rectangle() { this(1, 1); // Calls the constructor with length and width parameters } public Rectangle(int length, int width) { this.length = length; // Assigns the length parameter to the length instance variable this.width = width; // Assigns the width parameter to the width instance variable } public void printInfo() { System.out.println("Length: " + this.length); // Accesses the length instance variable using this keyword System.out.println("Width: " + this.width); // Accesses the width instance variable using this keyword } public static void main(String[] args) { Rectangle myRectangle = new Rectangle(); myRectangle.printInfo(); // Outputs "Length: 1" and "Width: 1" } }
In this example, the Rectangle class has two private instance variables, length and width, and two constructors. The first constructor has no parameters and uses the this keyword to call the second constructor, passing default length and width values. The second constructor takes a length parameter and a width parameter, and assigns the values to the instance variables. The printInfo() method uses the this keyword to access the instance variables and output the rectangle's length and width.
When an instance of the Rectangle class is created using the first constructor, the default length and width values are assigned to the instance variables, and the printInfo() method outputs the length and width to the console.