Superclass & Subclass variable assignment question

Maximilian

Lifer
Feb 8, 2004
12,604
15
81
Im still at the very beginning here, learning terminology, simple code etc so i hope ive got it right.

1. Superclass declared variables can be assigned to Subclass objects but with a loss of the Subclasses functionality when referenced through the Superclass variable

but

2. Subclass declared variables cannot be assigned to Superclass objects at all

Why not? Surely it would be a similar situation either way except in number 2 the object would be the part that does not understand any Subclass specific commands.

I don't see why anyone would mix/match anyway but its for the purpose of learning :)
 

Stuxnet

Diamond Member
Jun 16, 2005
8,392
1
0
Consider the superclass (aka base class) "vehicle" and two subclasses "car" and "boat".

"car" will define a property List<Wheel> Wheels. If things worked the way you would suggest, the base class would assume the Wheels property and, as such, it would then be inherited by the Boat subclass, which wouldn't make sense at all.

This highlights why it's so important to carefully design your object graph - otherwise you get nonsensiclal relationships.

Also, be careful about how you state things. Superclass variables aren't "assigned" to their subclasses; they're inherited by their subclasses and therefor callable against their subclasses. Also, we prefer the term "members" instead of "variables.". "members" includes simple fields, properties (with accessor methods), methods, etc.