Java This Keyword

  • StudentMia 

    August 24, 2021 at 2:11 pm

    Definition and Usage

    The this keyword refers to the current object in a method or constructor.

    The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter). If you omit the keyword in the example above, the output would be “0” instead of “5”.

    this can also be used to:

    Invoke current class constructorInvoke current class methodReturn the current class objectPass an argument in the method callPass an argument in the constructor call

  • StudentMia 

    August 24, 2021 at 2:17 pm


    Using this with a class attribute (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);
Viewing 1 - 2 of 2 replies
Reply to: StudentMia<span class="bp-verified-badge"></span>
Your information:

Original Post
0 of 0 posts June 2018