alpha09
alpha09

Reputation: 101

Java cast child to parent

Class Lion extends Animal.

Here is my code:

Animal a = new Animal();
Lion b = new Lion();
Animal c = (Animal) b;

Animal[] arr = { a, b, c };

for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i].getClass().getName());
    arr[i].run();
}

The result is:

test2.Animal

Animal Run...

test2.Lion

Lion Run...

test2.Lion

Lion Run...

From the example seems that "c" is a "Lion", not an "Animal". Why is that happening?

Upvotes: 8

Views: 32581

Answers (4)

ling_jan
ling_jan

Reputation: 99

A cast doesn't make the referenced object change its type, it just restricts itself to the methods of the supertype. You couldn't cast a Banana to an Animal for these reasons.

The cast in your line

Animal c = (Animal) b;

happens automatically anyways. You just need to specify your cast when you downcast:

Animal a = new Dog();
Dog d = (Dog) a;

But both a and d still point to a Dog in the heap and will thus use the instance methods of the Dog class if they override the methods of the Animal class. In other words, a is a Dog, but as long as it is declared as (or typecast to) an Animal, it can only use Animal methods.

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1075597

From the example seems that "c" is a "Lion", not an "Animal". Why is that happening?

Because c is a Lion:

Lion b = new Lion();   // Creates a Lion
Animal c = (Animal) b; // Refers to the Lion through an Animal variable

Now, c is an Animal-typed reference to a Lion object. The object is still a Lion, it's just the reference to it is limited to Animal stuff. So when you ask that object what its class is (not what your interface to it is in the c variable / third entry in your array), it tells you it's a Lion.

This is exactly like this situation:

Map m = new HashMap();

The m reference is typed Map and so you can only use it to access the things the Map interface defines, but the object it's referring to is a HashMap instance.

Upvotes: 12

mnd
mnd

Reputation: 2789

Your object c is a reference to an object, and the object must be of type Animal or any sub class. Just because the object reference is Animal doesn't guarantee that the object is an Animal, it just means that it will behave as an Animal, and you can call all of the methods on that class that you want. This is part of Polymorphism.

Upvotes: 1

Mena
Mena

Reputation: 48444

You are invoking getClass.

Method invocation resolves at runtime, hence it prints Lion and not Animal.

Upvotes: 2

Related Questions