-->

Java: Superclass and subclass

2019-06-05 18:09发布

问题:

  1. Can a subclass variable be cast to any of its superclasses?
  2. Can a superclass variable be assigned any subclass variable?
  3. Can a superclass be assigned any variable?
  4. If so, can an interface variable be assigned a variable from any implementing class?

回答1:

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?



回答2:

  • Yes
  • You can assign a subclass instance to a superclass variable
  • Huh?
  • You can assign an instance of a class to a variable of any interface type that the class implements


回答3:

Just for the sake of clarity, consider:

class A extends B implements C {  }

Where A is a subclass, B is a superclass and C is an interface that A implements.

  1. A subclass can be cast upwards to any superclass.

    B b = new A();
    
  2. 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 a = new B(); // invalid!
    
  3. A superclass can be assigned to any variable of appropriate type.

    A q = new A(); // sure, any variable q or otherwise...
    
  4. A class may be assigned to a variable of the type of one of its implemented interfaces.

    C c = new A();
    


回答4:

Can a subclass variable be cast to any of its superclasses?

Yes

And can a superclass variable be assigned any subclass variable?

Yes

Can a superclass be assigned any variable?

Yes

If so, can an interface variable be assigned a variable from any implementing class?

Yes



回答5:

Yes, that's usually the main idea behing polymorphism.

Let's say you have some Shapes: Circle, Square, Triangle. You'd have:

class Shape { ... }

class Circle extends Shape { ... }

class Square extends Shape { ... }

class Triangle extends Shape { ... }

The idea of inheritance is that a Circle is-a Shape. So you can do:

Shape x = ...;
Point p = x.getCenterPosition();

You don't need to care about which concrete type the x variable is.