DerivedClass b = new DerivedClass(); b.methodName(parameter)
The base class can be cast to a derived class only if the BaseClass object is refering to a Derived class object at runtime. eg. DerivedClass b = new DerivedClass();
BaseClass a = b;
b = (DerivedClass)a;
If the BaseClass object refers to an object of the type BaseClass or any other class other than the DerivedClass it would give you a ClassCastException.
Joined: Feb 07, 2005
Originally posted by Mark Lybarger: in java i can't do something like: BaseClass a = new BaseClass();
DerivedClass b = (DerivedClass) a;
is there some utility to _cast_ a base class to a derived class? I don't want to have to implement a clone method just to invoke the getters on the base, and the setters on the derived.
i have an ejb which returns some classes. another ejb takes those classes as arguments, but i need to extend them locally, and add some information about them.
Actually there is a good reason your code won't work. If an object reference is of type A, and B is a subclass of A, it is not necessarily true that the object is of type B. For example, a String is an Object, but an Object isn't necessarily a String.
Having the base class contain abstract getter and setter methods, and having the parameter type of the method be the base class would be the better way to go.
Joined: Jul 11, 2001
Originally posted by Mark Lybarger: is there some utility to _cast_ a base class to a derived class?
That's not possible, as the derived class could have additional fields - what values should those have?
What you should do is rethink your design. Perhaps the derived class shouldn't inherit the base class as all, but have a reference to an instance of it?
Can you tell us more about the design?
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus