0

I'm a beginner to coding and I recently learned about this and toString(). I'm not exactly sure what this is and what it does. Can someone explain it in simple words?? Also, when do I have to use it and when do I not?

One more question, why don't we have to use this in the toString() method if we already used it in a constructor?

Thank you so much

ywbaek
  • 2,971
  • 3
  • 9
  • 28
Alex Nam
  • 1
  • 2

3 Answers3

1

This is to refer to the current object. This is in contrast to "super" which refers to the current objects parent.

Usually "this" is used to distinguish instance variables from parameters. For example:

public class Person {
   private String name;

   public Person(String name) {
      this.name = name;
   }
}
NomadMaker
  • 447
  • 1
  • 5
  • 9
0

this is used to call Current Object/Current method and toString is used to convert any datatype into String. Like int into String. This is a keyword in java and toString is a predefined method.

Panciz
  • 2,183
  • 2
  • 30
  • 54
0

If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the string representation of the object. So you can print and see the value.

If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.

https://www.javatpoint.com/understanding-toString()-method