The reason your example works is actually due to the utility of toString() . You combine the String ( name ) object and the int ( age ) literal with the String ( ", " ) literal in your print statement. What this does is implicitly call toString() for everything concatenated. The String object has the toString() method defined in it, which returns the contents of the String internal char array for concatenation. int just uses its integral value as a primitive (although there may be some autoboxing that happens there in Integer , but it just ends up calling the toString() method defined in the Integer class).
What you really should try is to print your actual Daughter object (I use Daughter Daughter with this standard Java practice for class names):
public static void main(String args[]) { Daughter d = new Daughter("Elizabeth", 7); System.out.println("Daughter: " + d); }
You will notice that your result will look something like this:
Daughter: Daughter @ a62b39f
This is because you do not have the toString() method defined in your Daughter class, so it uses the return value of the default toString() / a> method , which is defined in the java.lang.Object class ("Mother of all objects", as some people call it, since all objects in Java are ultimately inherited from java.lang.Object ). This default method, toString() simply prints the class name and the storage location in which this particular object is located (technically the hash code of the object, but this is usually just a memory address, which is usually not so useful).
If you define the toString() method in your Daughter class as follows:
public String toString() { return this.name + ", " + this.age; }
then you should get a conclusion like this
Daughter: Elizabeth 7
when you call System.out.println("Daughter: " + d); to its main method (or elsewhere, the toString() method is called, explicitly or implicitly, on any Daughter object).
source share