-1

I am struggling to understand a specific usage of "this" keyword. What I don't understand here is why the printPerson() method invokes the toString() method.

public class Person {
    private String name;
    private int age;

    public Person(String aName, int anAge) {
        name = aName;
        age = anAge;
    }

    /** @return the String form of this person */
    public String toString() {
        return name + " " + age;
    }

    public void printPerson() {
        System.out.println(this);
    }
}

public class Driver {
    public static void main(String[] args) {
        Person mete = new Person("Mete", 21);
        mete.printPerson();
    }
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • printPerson() is a method of an object. To reference the object from within you use this. – mayamar Apr 12 '19 at 19:18
  • 1
    `this` keyword refers to the object, on which the method is invoked. And in this statement `System.out.println(this);` `this` is being passed to `println` which converts any object to string. And for converting an object to string form, it checks if the class of object implements `toString` method, then it invokes the `toString` method else invokes the method of super class of object's class which if none found, then calls `Object` class's `toString` method. – Pushpesh Kumar Rajwanshi Apr 12 '19 at 19:19
  • Also see [What is the meaning of "this" in Java?](https://stackoverflow.com/questions/3728062/what-is-the-meaning-of-this-in-java). – Slaw Apr 12 '19 at 19:20

1 Answers1

0

Every class in Java is directly or indirectly derived from the Object class. If a Class does not extend any other class then it is direct child class of Object and if extends other class then it is an indirectly derived. Therefore the Object class methods are available to all Java classes.

There are currently 9 methods in Object class and toString() is one of them.

If you are defining toString() method in your class it means you are overriding this method as it already present in its super class (i.e. Object class).

System.out.println requires anyhing in string format to display. If you have a class like this MyClass myClass = new MyClass(); System.out.println(myClass); In this case myClass.toString(); will be called and whatever is defined in toString() will be displayed. If myClass doesn't have its own toString() method then the Object.toString() will be called and displayed.

In your case this refers to the current class, hence System.out.println(this) calls to its own toString() as you are overriding it. And if you remove your toString() defination then Object.toString() will be called without any compation error.

Md Shahbaz Ahmad
  • 345
  • 4
  • 12