• 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 in Generics. pl help

 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anyone please help me in understanding the following. This is from the K&B MasterExam.

Given that CharSequence is an interface implemented by both the String and StringBuilder classes, and then given the following method
public <S extends CharSequence> S foo(S s){
//INSERT HERE

}
Which of teh following can be inserted here to compile and run without error? choose all that apply
A. return s
B. return(Object) s;
C. return s.toString();
D. return new StringBuilder(s);
E. return (S) new StringBuilder(s);
F. return null;

The answer is A. and F
why not D or E??

Thank you
 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can't return a stringbuilder or stringbuffer because you're not guaranteed that one of those objects are going to be the one "created" in the generic function. <S> could be something other than a buffer or builder -- or something that cannot be stuck into the constructor of StringBuilder, and then the return would be incorrect and not match what the method header says.
 
Ranch Hand
Posts: 893
Tomcat Server Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The keyword extends is somewhat misleading because it also applies to interfaces. In your example the interface is the generic type. String and Stringbuffer are a classes and not an interface so they could not be returned.

If they implement the interfaces you can use them, but only the methods which are defined by the interface. So be aware extends in generics could also apply for interfaces.
 
reply
    Bookmark Topic Watch Topic
  • New Topic