Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

this

Example

Utilizing “this” with a class attribute named “x”:

public class Main {

  int x;

 

  // Constructor with a parameter

  public Main(int x) {

    this.x = x;

  }

 

  // Call the constructor

  public static void main(String[] args) {

    Main myObj = new Main(5);

    System.out.println(“Value of x = “ + myObj.x);

  }

}

Definition and Usage

The this keyword denotes the current object within a method or constructor.

The this keyword is frequently employed to disambiguate between class attributes and parameters sharing the same name, especially when a class attribute is overshadowed by a method or constructor parameter. In the provided example, excluding the keyword would yield an output of “0” instead of “5”.

Additionally, “this” can be employed to:

  • Call the current class constructor
  • Invoke a method within the current class
  • Return the current class object
  • Supply an argument in a method call
  • Provide an argument in a constructor call