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 trialjuan esquivel
1,190 Pointsplease help.. i don't understand type casting .. I've watch over and over but it just doesn't click
what is type casting and were can i learn more "type casting in java"
1 Answer
João Elvas
5,400 PointsHello buddy,
It is really simple, don't worry.
As you should know by now, Java is an object oriented language, so guess what?! Everything is an object!
That means every object inherits from the class Object, so a String is an object, Integer is an object, your class instances are objects.
Now a bit of code:
class Animal{
public void walk(){
// doesn't matter
}
}
class Cat extends Animal{
@Override
public void walk(){
// doesn't matter
}
public void jump(){ // cats jump a lot :p
// doesn't matter
}
}
Now using those classes... without cast.
Animal a = new Cat();
a.speak(); // we are making speak on an Animal and that is impossible so we get: Compile Error
And now lets use cast
Animal a = new Cat();
Cat b = (Cat) a
b.speak(); // Now we are doing it on a cat as we made sure b is a Cat so there will be the speak method.
Good luck!