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

  1. 'this' refers to current object
  2. this.field = parameter
  3. Resolves naming conflicts

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler