Downcasting vs Upcasting in Java
CharSequence l_sq0 = new String( "HelloWorld 0" );
System.out.println( "CharSequence: " + l_sq0.toString() );
// Downcasting CharSequence to String
System.out.println( "CharSequence: " + l_sq0.toString() );
// Downcasting CharSequence to String
String l_tstr2 = (String)l_sq0;
byte[] l_bytes = l_tstr2.getBytes();
System.out.println( "String: " + l_tstr2.toString() +
" Length: " + l_bytes.length );
String l_tstr = new String( "Hello World 1" );
byte[] l_bytes = l_tstr2.getBytes();
System.out.println( "String: " + l_tstr2.toString() +
" Length: " + l_bytes.length );
String l_tstr = new String( "Hello World 1" );
// Upcasting String to CharSequence
CharSequence l_sq = (CharSequence)l_tstr;
CharSequence l_sq = (CharSequence)l_tstr;
System.out.println( "String: " + l_tstr.toString() );
System.out.println( "CharSequence: " + l_sq.toString() );
System.out.println( "CharSequence: " + l_sq.toString() );
In the above example, String which implemented CharSquence in java.lang has been upcasted and downcasted at two different places. So, that is allowed.
Need a quick answer? Get one in minutes from people who know. Ask your question on Yahoo! Answers.
4 Comments:
This comment has been removed by the author.
so do you mean java support downcasting by default and we have to do explict upcasting. is it correct?
This comment has been removed by the author.
Great explanation! I also thought this explanation of downcasting was helpful as well:
http://www.programmerinterview.com/index.php/java-questions/downcasting-in-java/
Post a Comment
<< Home