0

What code should I add to print "123"?

class people {
    String name = "123";
    String FinalName ;

    void getName() {
        String name = "456";
        System.out.println(name);
    }
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99

1 Answers1

1

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

So effectively you use it for multiple things:

  • clarify that you are talking about a field, when there's also something else with the same name as a field
  • refer to the current object as a whole
  • invoke other constructors of the current class in your constructor

Try this below:

class people {
    String name = "123";
    String FinalName ;

    void getName() {
        String name = "456";
        System.out.println(this.name);
    }
}

From here and here

Community
  • 1
  • 1
Abhishek Kulkarni
  • 1,747
  • 1
  • 6
  • 8