In K&B book, there's a question like below:
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 th following can be inserted at //INSERT HERE to compile and run without error?
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;
Answer : A and F.
I'm not sure whether D is correct, so I wrote the code below:
Line 4 runs method foo(), no problem; Line 5 prints foo()'s return value, an exception is thrown:
Exception in
thread "main" java.lang.ClassCastException: java.lang.StringBuilder cannot be cast to java.lang.String
at Test.main(Test.java:5)
I think both Line 4 and 5 should throw exceptions. Could someone explain to me why there's no exception at Line 4?
Thanks.