Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a question about casting between a base class and its child classes:

(1) Why is this allowed?

BaseClass b = new ChildClassA();
ChildClassA c = (ChildClassA)b

(2) Why is this not allowed?

ChildClassA c = (ChildClassA)new BaseClass();
BaseClass b = (BaseClass)c;

(3) Why is this allowed?

BaseClass b = new BaseClass();
ChildClassA c = (ChildClassA)c;

(4) Why is this allowed?

ChildClassA c = new ChildClassA();
BaseClass b = (BaseClass)c;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
195 views
Welcome To Ask or Share your Answers For Others

1 Answer

The reasons the cast is either allowed or not allowed is the basics behind inheritance.

A child class (or a derived class) is always a base class, but the opposite is not true.

To explain, let's use some more real world names for your example classes:

class Animal
{
}

class Dog : Animal
{
}

class Cat : Animal
{
}

So for your example (1):

Animal b = new Dog();
Dog c = (Dog)b

This is true because all Dogs are Animals and your Animal b is actually a dog so the cast is successful.

For your example (2):

Dog c = (Dog)new Animal();
Animal b = (Animal)c;

This is impossible because you are assigning an Animal object to a Dog, but you know that not all animals are Dogs, some animals are cats.

And for examples (3) & (4):

Dog c = new Dog();
Animal b = (Animal)c;

This is the same as your example 1 above. All dogs are animals, so any dog can be classified as an animal and cast (in fact you don't need the cast, there would be an implicit cast and you can write it as Animal b = c;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...