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?
Ernest Friedman-Hill
,
author and iconoclast
staff
// 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;
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 ]
Ernest Friedman-Hill
,
author and iconoclast
staff