Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

getting weird output  RSS feed

 
budsy remo
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • 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" ?


 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks a lot guys.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!