olyanren
olyanren

Reputation: 1458

Create subclass object from another subclass object

There are three classes. One of them is parent class, and others are subclasses. For example:

Parent Class: Parent

Subclasses: SubClass1, SubClass2

My question is that how can I convert SubClass1 object into SubClass2 object without typecasting exception ?

Upvotes: 2

Views: 176

Answers (6)

user447586
user447586

Reputation: 186

Actually it's possible!! if you don't care about the lose of data in the new object.

class Parent{
    String A;
    String B;
    public String getA();
    public String setA();
    public String getB();
    public String setB();
}
class SubClass1 extend Parent{
    String C;
    public String getC();
    public String setC();
}

class SubClass1 extend Parent{
    String D;
    public String getD();
    public String setD();
}

public SubClass1 convertTOSubClass2(SubClass2 obj2){
    SubClass1 obj1 = new SubClass1();
    obj1.setA(obj2.getA());
    obj1.setB(obj2.getB());
    ... 
    return obj1;
}

In this case, we simply ignore the C and D. I think it's OK for a few Fields (A,B) to set, but no good for many Fields(A-Z) or even Parent has Parent with many fields...

I am also looking for better/elegant solution, something like "copy all fields of parent class object", because sometimes we do want to reuse the data of the existing object.

== UPDATE ==

Apache BeanUtils: copyProperties(Object,Object) could be helpful.

Upvotes: 0

Roger Lindsjö
Roger Lindsjö

Reputation: 11543

You can't, and it would not really make sense to. Imagine you parent class being "Animal" and subclass1 an Elephant while subclass2 is a Mouse, what you are asking is for a way to look at the Elephant as if it was a Mouse.

Upvotes: 1

bragboy
bragboy

Reputation: 35542

You can fake the compiler but runtime you are assured to get ClassCastException

Upvotes: 1

Sean Owen
Sean Owen

Reputation: 66886

Say that the parent is Fruit and the subclasses are Banana and Apple. You are asking how to make a Banana into an Apple? You can't. A banana isn't an apple. The exception is telling you exactly that.

Upvotes: 1

Petar Ivanov
Petar Ivanov

Reputation: 93030

You can't do that, because SubClass1 might have a member that SubClass2 doesn't and the other way around.

Upvotes: 1

Tudor
Tudor

Reputation: 62439

You can't, unless you create an is-a relationship between them. Sibling type instances cannot be cast to eachother.

You will have to do something like:

SubClass2 extends Parent
SubClass1 extends Subclass2

Now both inherit from Parent and you can write

Subclass2 obj = new Subclass1();

Or do the reverse.

Upvotes: 2

Related Questions