• Post Reply Bookmark Topic Watch Topic
  • New Topic

subclass sub = new superclass() ??  RSS feed

 
jaspreet atwal
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
 
Jan van Mansum
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suppose you meant to say that
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jan van Mansum:
I suppose you meant to say that


Yes, thank you.
 
jaspreet atwal
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much for your replies! I understand a lot better now.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!