简体   繁体   English

从另一个子类对象创建子类对象

[英]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 家长班: Parent

Subclasses: SubClass1, SubClass2 子类: SubClass1, SubClass2

My question is that how can I convert SubClass1 object into SubClass2 object without typecasting exception ? 我的问题是,如何在没有类型转换异常的情况下将SubClass1对象转换为SubClass2对象?

You can't, unless you create an is-a relationship between them. 除非您在它们之间创建is-a关系,否则您就不能这样做。 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 现在两者都继承自Parent ,您可以编写

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 . 在这种情况下,我们只需忽略CD即可 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... 我认为可以设置几个字段(A,B),但是对于许多字段(AZ)甚至对父级都有很多字段的父级都没有好处。

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. Apache BeanUtils :copyProperties(Object,Object)可能会有所帮助。

您不能这样做,因为SubClass1可能具有SubClass2没有的成员, SubClass2

Say that the parent is Fruit and the subclasses are Banana and Apple . 假设父级是Fruit ,子类是BananaApple You are asking how to make a Banana into an Apple ? 您在问如何将Banana制成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. 假设您的父类是“动物”,而子类1是大象,而子类2是鼠标,那么您想要的是一种看似大象的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM