Welcome to the Treehouse Community
Looking to learn something new?
Matthew Francis6,967 Points
What is the purpose of "Casting" and whens should you use it?
After watching an introductory video on it I understand how it works and all but I'm unsure when and why you should use it, an explanation would be great!
Wout Ceulemans17,603 Points
Lets say you have an instance of type Object. You are certain that this object is a String, but you cannot use any String related methods on your instance because it is still of type Object. What you then can do is cast it to a String, and thus be able to use String related methods.
Object o = "Hello"; String s = (String) o;
You can cast an object to another type to obtain methods and fields that where otherwise not accessable. Be always sure that the object can be casted to the target type. You can always cast an object to one of his parent class (eg: String to Object). Casting a parent class to a childclass is also possible, but this could go wrong and throw an ClassCastException.
Casting to parent class:
String s = "Hello"; Object o = (Object) s;
Casting to child class:
Integer i = new Integer(5); Number n = (Number) i; Integer i2 = (Integer) n;
I'm not a Java professional, but I hope this gives you a good explanation.