Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Base class and an extended class...

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two objects...

A Base object and an extended object...

I have a method that returns a BaseObject. I wanted to convert my BaseObject to my extended object... How do I do it?

I cant say: (ExtendedObject)BaseObject

That gives me a ClassCassException

What should I do?
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe you could define a constructor for your sub-class that takes a parent class instance as a parameter.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot downcast the reference to the extended type unless the actual runtime type of the object is, in fact, the extended type.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This may be a design problem raising it's hand and asking for a fix. One very common problem is using subclassing where roles would be more appropriate. For example one might model a base person class and subclasses for student and instructor. Then when a grad student teaches a course you find you can't really change her from student to instructor. A better model might have a concrete person with pluggable behavior - do some student behavior now, do some instructor behavior later.

Did that makes sense? Does it connect with your situation??
 
Emanuel Kadziela
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your method's signature can return a base object, but the actual entity it returns must be the object you intend to cast to. I will give you an example, but I must say this is really bad design and should be replaced with interfaces plus some of what the other commentors' said.



You can also always use instanceof as a last resot to avoid ClassCastExceptions.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic