1

This is the text from the book Data Structures and Algorithms in Java by Goodrich from chapter one giving reasons for use of the this keyword.

To allow one constructor body to invoke another constructor body. When one method of a class invokes another method of that same class on the current instance, that is typically done by using the (unqualified) name of the other method. But the syntax for calling a constructor is special. Java allows use of the keyword this to be used as a method within the body of one constructor, so as to invoke another constructor with a different signature.

Why does it say unqualified name of the other method?

nayan
  • 21
  • 3

1 Answers1

7

There are two ways to call a method from another method. Generally, you'll refer to its name qualified. If I've got an object foo and it has a method frobnicate, I'll do

foo.frobnicate();

Now, if I'm already inside the right instance (say, I'm calling frobnicate from another method on foo), then I use the special variable this.

this.frobnicate();

But Java allows us to, as a shortcut, omit this and simply call the method name. The following is an example of calling the method with its unqualified name:

frobnicate();

The this. is implied.

On the other hand, the point the paragraph is trying to make is that constructors are special. We don't call constructors as foo.frobnicate(); we just say Foo(). So there has to be special syntax to call a constructor from within another constructor, i.e. this().

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116