Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt about method signature StringBuilder, Chapter 5, page 272 (K&B7)

 
Roger Jenkins
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On page 272, regarding the methods in the StringBuilder-class, the headline regarding the toString() method says:
public String toString()

but shouldn't that be:
public StringBuilder toString()

since it is a StringBuilder method and not a String method?

(This post originated in the K&B7 errata thread)
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roger Jenkins wrote:but shouldn't that be:
public StringBuilder toString()

since it is a StringBuilder method and not a String method?

You are incorrect! The study guide is spot-on. This is a method signature of the StringBuilder class and if you have a look at the API documentation of the StringBuilder class, you'll notice that the correct method signature of the toString() method isand not (as you suggested)And if you think about it a little bit, it makes sense: the toString() method is defined in the Object class and defines a String as the return type. Just like in the String class, this method is overridden in the StringBuilder class as well. And to have a valid override you need the same method signature and return type (or a covariant return), so that's why you can't have the method signature you have suggested, because it's an invalid override and also an invalid overload (because the parameter list is not different from the method with the same name defined in the Object class).

Hope it helps!
Kind regards,
Roel
 
Roger Jenkins
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for clearing this up! Yes, it helps!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic