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 trialabdijabar sambul
1,063 Pointswhen the Craig type casted the object into a Treet. what will the obj contain, is it the treet or the secondTreet ?.
Hello Good people, when Craig type caste the object into a Treet. what will the obj contain, is it the treet or the secondTreet ?. And my other question is can you typecast Object as a Treet (upward Casting) without first type casting Treet as an Object (down casting).since in java-repl if you create an Object and try to type caste explicitly as a Treet it will through an error(java.lang.ClassCastException: java.lang.Object cannot be cast to com.teamtreehouse.Treet).
thanks for your time.
Anthony Albertorio
22,624 Pointsgreat explanation sjules
1 Answer
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 PointsJust paraphrasing the above comment by sjules.
Whatever is passed in to the compareTo method (likely a Treet) will be an Object. Everything in java is an instance of the the parent Object class, therefore it is safe to just store the argument as an Object. However the parent Object Class doesn't have all of its children methods and properties (with the children methods and properties being the class Treet methods and attributes) So, to ensure that you can access the properties and methods of Treet, you must cast the Object as a Treet
eodell
26,386 Pointseodell
26,386 PointsHi. Upcasting will work without problems. As a matter of fact that is what is happening in the method signature:
Whatever is passed in to the compareTo method (likely a Treet) will be an Object. Everything instance in java is polymorphic as every instance is the datatype of the reference as well as the parent Object class. So it is safe to just store the argument as an Object. But now that it is an Object, it doesn't have all of its children methods and properties (with the children methods and properties being the methods and properties belonging to the actual type that was passed in to the method in question. So, to ensure that you can access the properties and methods of Treet, you must cast that Object as a Treet:
(Treet) obj
Since this method is in the Treet class itself, the object that is passed in could be anything. Take the following from Example.java:
Since both treet and secondTreet are instances of the Treet class, theyboth will have the compareTo method. so you could use either one:
I hope that makes sense.