Complete the code to print the current object's name using this keyword.
public class Person { String name; public Person(String name) { this.name = name; } public void printName() { System.out.println([1].name); } }
The this keyword refers to the current object instance. To access the instance variable name, use this.name.
Complete the constructor to call another constructor in the same class using this keyword.
public class Box { int width, height; public Box() { this(10, 20); } public Box(int width, int height) { this.width = width; this.height = height; } public void printSize() { System.out.println("Width: " + width + ", Height: " + height); } }
The this keyword can be used to call another constructor in the same class. Here, this(10, 20); calls the parameterized constructor.
Fix the error by completing the code to correctly refer to the instance variable value when parameter name is the same.
public class Counter { int value; public void setValue(int value) { [1].value = value; } }
When parameter name shadows instance variable, use this to refer to the instance variable explicitly.
Fill both blanks to complete the method that returns the current object's string representation using this keyword.
public class Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public String toString() { return "Point(" + [1].x + ", " + [2].y + ")"; } }
The this keyword refers to the current object. Use it to access instance variables x and y inside the toString method.
Fill all three blanks to complete the constructor chaining and instance variable assignment using this keyword.
public class Rectangle { int width, height; public Rectangle() { this([1], [2]); } public Rectangle(int width, int height) { [3].width = width; this.height = height; } }
The no-argument constructor calls the parameterized constructor with values 10 and 20 using this(10, 20);. Inside the parameterized constructor, this is used to assign the instance variable width.