Using 'this' Keyword in Java: Explanation & Practice
Use 'this' to refer to current instance
Problem summary
Create a Rectangle class where constructor uses 'this' to distinguish parameters from fields.
Starter code
// Create Rectangle with:
// - int width, height
// - constructor using 'this'
// - int area() method
public class Main {
public static void main(String[] args) {
// Create rectangle 5x10 and print area
// Output: Area: 50
}
}Expected output and test cases
- Calculate area
Area: 50
Hints
- 'this' refers to current object
- this.field = parameter
- Resolves naming conflicts
Related OOP Basics exercises
- Practice Static Members in Java
- Practice Method Overloading in Java
- Practice BMI Calculator Class in Java
Practice all OOP Basics exercises · Run this idea in the Java compiler