Casting allows you to use functionality not present in an interface but present in an implementation. I am refering to an 'interface' in the object-oriented sense, not as a class with that keyword in the declaration. You use it to gain more control of the finer details of a class (which is not always a good thing). Example: ... URL url = new URL("http://site/"); URLConnection uc = url.openConnection(); // since I know this is an http connection, // I'll use http specific methods not available // in a normal URLConnection HttpURLConnection huc = (HttpURLConnection) huc; // I'm posting an html form. You can't do this // with ftp or file protocols. huc.setRequestMethod("POST"); ...
It depends on what YOU mean by casting. Casting is mearly the conversion of one reference-type to another. The advantage is that you get your program to work. Look at the following example. Child extends super.
Did that enlighten you? /Mike
Amir Abbas Mooman
Joined: Aug 19, 2001
Originally posted by Amir Abbas Mooman: what is the advantage of casting
If you are looking for The advantages of Type Casting. Suppose If you want to the value of int data type variable assigned into the short data type variable. You will get an error. Offcourse (In general life) its impossible to store full volume of water filled in a jug into a glass. Whereas we can store the glass water into the jug.
But with type casting it is made possible to assign the values of different type of variables to each other. The larger type to the smaller or smaller to larger. (int to short or int to long, byte to short or short to byte, vice versa) However we may loose some information, like if we pour the water of jug in a glass (if we want to assign the larger value into the smaller type variable).
Read page 43 of Khalid Mughal's book for beginners.