• 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:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

getting weird output

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


when i type
java Q8 12
i get

It's a Square
144.0
Rectangle@19821f

Why do i get "Rectangle@19821f" ?


 
author
Posts: 23931
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

budsy remo wrote:
Why do i get "Rectangle@19821f" ?



When you print out the object, System.out.print() will call toString() on the object to get a string that it can print. And since, you didn't implement the toString() method, it will inherit it from the Object class. The toString() method of the Object class generates a string with the class type and the identity hash code, which is what you see.

Henry
 
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As Mr. Wong said, you defined a class called Rectangle but did not override the toString() method so when you tried to print the Rectangle instance at line 15, it called the default toString() method as implemented in the Object class, which Rectangle extends. If you override the toString() method, you can display whatever you want.

In the code below, I modified your Rectangle class to implement a toString() method. Note the @Override annotation on line 35. This is not mandatory but tells the compiler the method that follows overrides a method of the base class. If you get the syntax of the method wrong, the compiler will tell you.
 
budsy remo
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot guys.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic