- 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?
-
3You should make a clear distinction between the concept of a variable and a value. As it is now, your question is very confusing.Matti Virkkunen– Matti Virkkunen2011-02-03 02:03:27 +00:00Commented Feb 3, 2011 at 2:03
-
You may want to read up on contra-/covariance, as the answer will change if you slightly change your question. You can get a rough idea where it will be a different answer by reading this: stackoverflow.com/questions/1184295/java-covariance-questionJames Black– James Black2011-02-03 02:04:48 +00:00Commented Feb 3, 2011 at 2:04
5 Answers
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?
Comments
- 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 Comments
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();
Comments
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
2 Comments
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.