• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Sheriff
Posts: 11604
178
Hibernate jQuery Eclipse IDE Spring MySQL Database AngularJS Tomcat Server Chrome Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for clearing this up! Yes, it helps!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic