• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Explain output

 
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


output:43

can anyone explain me as to what the heck is happening here,
i was expecting as to nothing would be printed here.
 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If an object is printed using a system.out.println then its method is called if the class overrides it else its hashcode is printed.

As class B provides implementation for toString hence the output 43.
 
Ranch Hand
Posts: 244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why nothing will be printed?
If you did not override the method toString() in any classes, then the default String representation would have been printed i.e ClassName + "@" + Integer.toHexString(hashCode()) of the object because that is the default behaviour of object written in Object class's toString() method.
Generally when we print object this is printed.

As because you have overridden the toString() method that is why it is giving output 43 , first calling super method's toString() (i.e "4") then Sub class's toString() (i. "3") method.

If you had overrided the toString() method only in class B then output would have been different. In that case first it would call the default implementation of Object class then it will append "3" of the toString() method of B to the default result of Object class's toString() method.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic