File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assignment of references

 
geeta rai
Ranch Hand
Posts: 48
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm confused as to how the assignment of the references of superclass object to subclass variables and vice versa done?
 
Vishy Karl
Ranch Hand
Posts: 116
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is easy if you try to understand.
Conversion of instance of
Subclass -> Base allowed without any cast.
but

Base -> Subclass not allowed without cast.
(It is same like that for primitives).
Even when you cast from Base -> Subclass the subclass should actually contain the methods to be invoked using the subclass reference variable.
Search for examples you will find plenty of them,
Good luck.
 
Mohit Goyal
Ranch Hand
Posts: 65
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi well when u r assigning a subclass type to a superclass type u don't have to cast explicitly.
ex :
String s="hello";
Object o =s;
but when u r assigning a superclass type to a subclass type u have to explicitly cast it to a subclass type.Ex
Object o = new Object();
String s=(String) o;
But remember that in both cases the classes involved should be from the same inheritence tree. i.e. the classes must be related by inheritence.
otherwise u will get ClassCastException
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic