- 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?
Java: Superclass and subclass
6.7k views Asked by kenny AtThere are 5 answers
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.
A subclass can be cast upwards to any superclass.
B b = new A();
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!
A superclass can be assigned to any variable of appropriate type.
A q = new A(); // sure, any variable q or otherwise...
A class may be assigned to a variable of the type of one of its implemented interfaces.
C c = new A();
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?
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.