- Can a subclass variable be cast to any of its superclasses?
- Can a superclass variable be assigned any subclass variable?
- Can a superclass be assigned any variable?
- If so, can an interface variable be assigned a variable from any implementing class?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Yes
Yes
Yes
Yes
Just for the sake of clarity, consider:
Where
A
is a subclass,B
is a superclass andC
is an interface thatA
implements.A subclass can be cast upwards to any superclass.
A superclass cannot be cast downwards to any subclass (this is unreasonable because subclasses might have capabilities a superclass does not). You cannot do:
A superclass can be assigned to any variable of appropriate type.
A class may be assigned to a variable of the type of one of its implemented interfaces.
Yes, that's usually the main idea behing polymorphism.
Let's say you have some Shapes: Circle, Square, Triangle. You'd have:
The idea of inheritance is that a Circle is-a Shape. So you can do:
You don't need to care about which concrete type the
x
variable is.Are all dogs also animals?
Are all animals also dogs?
If you need an animal, and I give you a dog, is that always acceptable?
If you need a dog specifically, but I give you any animal, can that ever be problematic?
If you need something you can drive, but you don't care what it is as long as it has methods like .Accelerate and .Steer, do you care if it's a Porsche or an ambulance?