| Author |
Object from Subclass to Superclass
|
Pan Niko
Ranch Hand
Joined: Mar 19, 2011
Posts: 86
|
|
Hello,
Im wondering if you can "convert" a subclass's object to superclass's.
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
You can't. Objects can't change type. You can however change the reference type to the object:
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
Pan Niko
Ranch Hand
Joined: Mar 19, 2011
Posts: 86
|
|
|
And what happening if child has extra variables that Parent doesn't?
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
|
You'll lose scope to that variable/method. You can only access/invoke variables/methods that are defined in the parent. However if the Child class overrides one of these methods (not variables!) that method will be called instead of the method of the parent.
|
 |
Ivan Franko
Ranch Hand
Joined: May 30, 2011
Posts: 44
|
|
|
you lose extra variables...
|
 |
Pan Niko
Ranch Hand
Joined: Mar 19, 2011
Posts: 86
|
|
To make it clear
So if now do:
newParent_2 will just hold name? "Steven"??
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
No. Variables don't contain anything except a reference to an object. And the object always contains the same data no matter what type of variables contain references to it.
However the compiler doesn't let you access anything except variables and methods which are declared for the type of variable. So in your example, the Child object continues to contain everything which a Child object normally contains, but the Parent variable which refers to it can only access variables and methods from Parent.
|
 |
Ivan Franko
Ranch Hand
Joined: May 30, 2011
Posts: 44
|
|
|
|
 |
 |
|
|
subject: Object from Subclass to Superclass
|
|
|