Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Matthew Francis
Matthew Francis
6,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!

1 Answer

Wout Ceulemans
Wout Ceulemans
17,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.