Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures Getting There Type Casting

mohamadreza azadi
mohamadreza azadi
5,167 Points

i'm so confuesd about casing plz help

i'm so confused about casing and casing make new object of your object and i dont know why we used it ??? what's diffrents between upcasing and downcasing please help me:((((((

3 Answers

For example if you have a class called Dog and dog inherits from an Animal class and dog will also inherit from Object class that means that dog instance is technically also an animal instance and object instance

For example

if(dog instanceof Animal){ System.out.println("True"); } else { System.out.println("false"); }

The code above would print out true because dog is an instance of animal but if you did it reverse it would say false because Animal is not an instance of dog because Animal does not inherit from the Dog class but the Dog class inherits from the Animal class making the dog Instance also an animal instance.

I will talk about the differences about downcasting and upcasting

Let's say you downcasted Animal to be a dog this would work because the compiler knows that Dog is an object of animal

Let's say you upcasted this wouldn't work because Animal Is not known to the compiler to be a Dog. that's why you have to do this when you upcast. dog = (Dog)animal; What the (Dog) thing will do is that Animal will assume that it is a dog making the code work.

Also for objects to cast the classes must be inherited

If you need any more help just ask me

mohamadreza azadi
mohamadreza azadi
5,167 Points

if we don't inherit dog class into the animal class, we get false right? Peter Danglay

Cory Walker
Cory Walker
6,037 Points

Thanks Peter for really explaining the concepts of object casting. I was a little confused as well until I came across this question. I think the video would be more understandable if they used "animal class" and "dog class" as their examples versus Treet, which makes it hard to understand.

Yes we would get false.

You're welcome, Cory. No problem.