Playing with GAS
Playing with GAS

Reputation: 585

Class method called by only presenting object name

I have the following piece of code

public class DriverTester {
  public static void main(...){
    // test empty constructor
    Person p1 = new Person();
    System.out.println("p1: " + p1); 
  }
}

public class Person {
   private String name;
   // Empty constructor 
   public Person () {
   }
   // getter avoided for simplicity
   public String toString() {
     return "Mr.or Ms. "+this.name;
   }
}

It compiles, runs succesfully and shows "Mr or Mrs null". So, that would b e the result of calling the toString method.

I don't understand the syntax in of the print line method. How is it that simply the name of the object p1 runs a given method. How does it know which method to run? Shouldn't the syntax be

System.out.println("p1: " + p1.getName());

or

System.out.println("p1: " + p1.toString());

Thanks for any clarification

Upvotes: 2

Views: 180

Answers (2)

Reimeus
Reimeus

Reputation: 159844

PrintStream used by System.out.println uses String.valueOf

649     public void print(Object obj) {
650         write(String.valueOf(obj));
651     }

which in turn uses the Object's toString method provided the Object itself is not null, otherwise the literal "null" is returned.

2837    public static String valueOf(Object obj) {
2838        return (obj == null) ? "null" : obj.toString();
2839    }

Upvotes: 2

rgettman
rgettman

Reputation: 178303

When concatenating strings, such as in this line:

System.out.println("p1: " + p1);

Java will call the toString() method to convert any object to a String for concatenation. Java ensures that this method exists on all objects, because it's defined on the Object class, which every class implicitly inherits from.

Additionally, if a null is concatenated, then Java will convert that into the String "null".

The Java Language Specification, section 5.1.11, covers "String Conversion":

  • If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
  • Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

Upvotes: 4

Related Questions