Forums Register Login

subclass sub = new superclass() ??

+Pie Number of slices to send: Send
This maybe a very basic concept, but I am afraid I fail to understand this. Please help me clear the following query:
Why cannot we assign an object of Superclass to a subclass? Shouldn't this work as subclass inherits all attributes of a superclass?
+Pie Number of slices to send: Send
class Super { int x; }
class Sub { int y; }

// This isn't allowed, but let's pretend
Sub sub = new Super();

// This is why it's not allowed: we're trying to access the field y
// of an instance of the class "super". This would compile, but fail
// when the program ran.
sub.y = 3;

// But on the other hand, this is legal:
Super sup = new Sub();

// And this is fine because a Sub has an x, since it's
// a subclass of Super.
sup.x = 3;
+Pie Number of slices to send: Send
I suppose you meant to say that
+Pie Number of slices to send: Send
 

Originally posted by jaspreet atwal:
Why cannot we assign an object of Superclass to a subclass? Shouldn't this work as subclass inherits all attributes of a superclass?


There is an "is a" relationship between subclasses and superclasses. An instance of a subclass is an instance of the superclass. That is why you can assign an instance of a subclass to a variable of the superclass type - not the other way around!

[ November 06, 2007: Message edited by: Jesper Young ]
+Pie Number of slices to send: Send
 

Originally posted by Jan van Mansum:
I suppose you meant to say that



Yes, thank you.
+Pie Number of slices to send: Send
Thank you so much for your replies! I understand a lot better now.
Hug your destiny! And hug this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 876 times.
Similar Threads
constructor question
abstract class...help
K&B Book not complete ???
3 Questions
Protected Method access
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 23:51:31.