| Author |
String stuff
|
meeta gaur
Ranch Hand
Joined: Dec 05, 2012
Posts: 226
|
|
Example.java:12: error: incompatible types
String sub=s.subSequence(5,12);
^
required: String
found: CharSequence
1 error
String class implements CharSequence interface then why can't it hold returned object ?
|
OCAJP
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16811
|
|
meeta gaur wrote:
Example.java:12: error: incompatible types
String sub=s.subSequence(5,12);
^
required: String
found: CharSequence
1 error
String class implements CharSequence interface then why can't it hold returned object ?
All String objects are IS-A CharSequence, but not all CharSequence objects are IS-A String.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
meeta gaur wrote:String class implements CharSequence interface then why can't it hold returned object ?
Because CharBuffer, Segment, StringBuffer and StringBuilder also implement CharSequence and so the compiler doesn't know that it will definitely be a String that is returned.
You can override this by putting an explicit cast in your code
This says to the compiler - I know that the object returned from the method could be something other than a String, but I'm telling you it will be a String
Of course, if, at run time, something other than a String is returned, you will get a ClassCastException.
|
Joanne
|
 |
meeta gaur
Ranch Hand
Joined: Dec 05, 2012
Posts: 226
|
|
Thanks to all.
|
 |
 |
|
|
subject: String stuff
|
|
|