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 ?
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.
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(AZ) 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.
您不能这样做,因为SubClass1
可能具有SubClass2
没有的成员, SubClass2
。
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.
您可以伪造编译器,但可以确保运行时获得ClassCastException
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.