Two Laptop Bag
The moose likes Beginning Java and the fly likes Base class and an extended class... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Base class and an extended class..." Watch "Base class and an extended class..." New topic

Base class and an extended class...

Anthony Smith
Ranch Hand

Joined: Sep 10, 2001
Posts: 285
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

Joined: Jan 17, 2006
Posts: 1296
Maybe you could define a constructor for your sub-class that takes a parent class instance as a parameter.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
marc weber

Joined: Aug 31, 2004
Posts: 11343

You cannot downcast the reference to the extended type unless the actual runtime type of the object is, in fact, the extended type.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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??

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Emanuel Kadziela
Ranch Hand

Joined: Mar 24, 2005
Posts: 187
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.
I agree. Here's the link:
subject: Base class and an extended class...
It's not a secret anymore!