• Post Reply Bookmark Topic Watch Topic
  • New Topic

question about declare and create an object  RSS feed

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are 2 classes and one is subclass of another like below:



The first one is correct one but the second. I do not have a good explanation for that. I do know that
A reference variable can refer to any object of its declared type or any subtype of its declared type

and why not
A reference variable can refer to any object of its declared type or any supertype of its declared type

Im not convinced myself. Please help, thanks
 
Ranch Hand
Posts: 186
C++ Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"A super class reference variable can refer to any direct or indirect sub class object, but it reverse is not allowed."

And the reverse is not allowed becuse it is possible that super class might have members (privete) which are not available in sub class.
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try replacing A and B with more concrete examples:
 
Marshal
Posts: 56600
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
swaraj gupta wrote:"A super class reference variable can refer to any direct or indirect sub class object, but it reverse is not allowed."
That is correct, but please tell us where you found it, to avoid copyright problems, etc.
And the reverse is not allowed becuse it is possible that super class might have members (privete) which are not available in sub class.
That doesn't seem a very good explanation; looking at Rob's post with Dog and Animal gives an easier explanation to understand.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!