[Java] If we print the object reference what will be the output ?


Initially, when I'm trying to learn JAVA concepts quiet confusing for me.
If I print MyClass object reference it will print the hashcode with prefix "@".

      - Yes, It's fair enough!. 


             MyClass objectRef  = new MyClass(); 
                       System.out.println(objectRef); 

Output: @[hashcode]

But when I print the String or Collection object reference it's printing the string content and collection Object elements respectively.
   - Isn't it confusing ?
If you ask me why ?
  -  Because, String, Collection and MyClass are the objects with respective  references.
As all of them are object reference we will expect that String and Collection object references also print the  same hashcode, but it's printing the String content and Collection element.


Did we learn anything wrong? 
- Nothing wrong. 
It's time to understand the Inheritance.
As per sun-micro system doc every user defined class will be inherited from Object class


       System.out.println(objectRef); // Implicitly JVM call toString()
              System.out.println(objectRef.toString()); // This also give same output

So, when we create the object for MyClass it will call the parent class method named `toString();` which will print the Hashcode with prefix "@";

If we take the String class, it had own toString() method which is overriden from Object class to print the String content.



Same with Collection(ArrayList, LinkedList).
       ArrayList al = new ArrayList();
       System.out.println(al); // Implicitly JVM call toString()
           //   System.out.println(al.toString()); // This also give same output

But question is which class toString() method is calling.
Check this class hierarchy.



When we print the "al" it will call the "AbstractCollection" class "toString();" method which had functionality to print the collection element.




No comments:

Post a Comment