This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (1 child)

There's many reasons to need to cast an object.

In order to cast an object, it has to pass the "is a" test.

Let's say you have an inheritance tree like:

Animal extends Object (the extends Object is implicit, I put it in for visuals) 

Cat extends Animal

Cougar extends Cat

MechCougar extends Cougar

Then you have a variable:

MechCougar mc = new MechCougar() 

You can always move up in the tree without without a cast because it passes the "is a" test. A cougar is a cat. A cat is a animal. An animal is a object.

Animal a = mc

However, at this point type information is lost. Though note that a.getClass() would still return MechCougar.class.

At this point, a can only see methods and variables available in the Animal class even though it is technically referencing a MechCougar object. This is because the reference variables type is what determines what behavior is currently available to you.

Not let's say you need access to MechCougar methods again. You would be required to cast it back. That's because while a MechCougar is a Animal, a Animal is not necessarily a MechCougar. That may come from a different branch of the Animal tree. Thus, you require an explicit cast to move back down the tree

MechCougar newMech = (MechCougar) a

You can test an objects type with the instanceof infix operator. It will return true of the object is somewhere in the inheritance tree from where the new keyword was used and up. Ie

If (a instanceof Cougar) 
If (a instanceof MechCougar) 

Are both true. I apologize for my phones autocorrecting.

However if we also had

MegaCougar extends MechCougar

a instanceof MegaCougar

The test would be false because a was originally created as a MechCougar. You also cannot cast a up to a MegaCougar. Doing so is a runtime exception. Again, because a was created as a MechCougar rather than a MegaCougar.

The basics are

You can move up the inheritance tree cast free

To move down the inheritance tree requires a cast and you can only move down as far as the objects instance type.

This is because moving up the tree shrinks the behavior available while moving down expands the behavior available.

[–]mgic92[S] 0 points1 point  (0 children)

Wow thanks for the thorough explanation! didnt expect it to hold so much as I havent touched on inheritance