File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object from Subclass to Superclass

 
Pan Niko
Ranch Hand
Posts: 86
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Im wondering if you can "convert" a subclass's object to superclass's.
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't. Objects can't change type. You can however change the reference type to the object:

 
Pan Niko
Ranch Hand
Posts: 86
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And what happening if child has extra variables that Parent doesn't?
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll lose scope to that variable/method. You can only access/invoke variables/methods that are defined in the parent. However if the Child class overrides one of these methods (not variables!) that method will be called instead of the method of the parent.
 
Ivan Franko
Ranch Hand
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you lose extra variables...
 
Pan Niko
Ranch Hand
Posts: 86
Eclipse IDE Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To make it clear



So if now do:


newParent_2 will just hold name? "Steven"??
 
Paul Clapham
Sheriff
Pie
Posts: 20176
25
MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. Variables don't contain anything except a reference to an object. And the object always contains the same data no matter what type of variables contain references to it.

However the compiler doesn't let you access anything except variables and methods which are declared for the type of variable. So in your example, the Child object continues to contain everything which a Child object normally contains, but the Parent variable which refers to it can only access variables and methods from Parent.
 
Ivan Franko
Ranch Hand
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic