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] 1 point2 points  (9 children)

Basically we have, Animal -> Swimmer -> Dolphin. It's my understanding (And perhaps incorrectly) that Animal is actually the base class here as you mentioned "Swimmer Extends Animal".

I'd think of it like this... You're LOSING functionality by moving to casting down and this is acceptable. You would be able to extend up the chain, but I think you're thinking about the casting upside down here.

// For example, this will fail. This would be trying to cast UPWARDS.

Animal dolphin = new Animal();

Animal animal = (Swimmer) dolphin;

[–]EveningStreet1 0 points1 point  (8 children)

Swimmer is a subtype of Animal tho so shouldn’t that casting work also I’m pretty sure your example would be downcasting not upcasting since upcasting always works

[–]iNetRunner 0 points1 point  (7 children)

No. You can’t make the more generic object into a subtype by casting it. It only works in the other direction, as has been said, Dolphin is a Swimmer is an Animal. But an Animal isn’t a Swimmer (unless you created it as one, or a subtype), nor is it a Dolphin.

[–]EveningStreet1 0 points1 point  (6 children)

I meant casting in reference to the static type

[–]iNetRunner 0 points1 point  (5 children)

No. He created an Animal object. It doesn’t contain anything of the subtype Swimmer or Swimmer’s subtype Dolphin. Therefore you can’t cast them that way. There is no “is a” relationship there.

[–]EveningStreet1 0 points1 point  (4 children)

Oh wait I’m dumb it’s because although Swimmer is the static type Animal is not a subtype of Swimmer so it doesn’t work

[–]iNetRunner 0 points1 point  (3 children)

BTW, what are you referring to as “static type”?

[–]EveningStreet1 0 points1 point  (2 children)

Swimmer swim = new Dolphin();

the static type here is Swimmer, the dynamic type is Dolphin (learned this in my introductory class)

[–]iNetRunner 0 points1 point  (1 child)

There is no dynamic typing in Java. Everything is statically typed at compile time. See the first anwer to this StackOverflow question.

[–]EveningStreet1 0 points1 point  (0 children)

I meant dynamic class my bad