How to cast parent into child in Java

我们两清 提交于 2019-12-23 14:57:03

问题


I am doing this:

Child child = (Child)parent;

Which gives me an error, I found it isn't possible to do it like this. I don't know exactly why, but I think it should be possible, if Child class inherits from Parent class, it contains the Parent object data.

My questions are:

  • Why it doesnt work?


  • How can i make this work, without setting every single parent's attribute like this

:

class Parent{
    public int parameter1;//...
    public int parameter1000;
}

class Child extends Parent
{
    public Child(Parent parent)
{
        this.parameter1 = parent.parameter1;//...
        this.parameter1000 = parent.parameter1000;
}
}

回答1:


Well you could just do :

Parent p = new Child();
// do whatever
Child c = (Child)p;

Or if you have to start with a pure Parent object you could consider having a constructor in your parent class and calling :

class Child{
    public Child(Parent p){
        super(p);
    }
}
class Parent{
    public Parent(Args...){
        //set params
    }
}

Or the composition model :

class Child {
    Parent p;
    int param1;
    int param2;
}

You can directly set the parent in that case.

You can also use Apache Commons BeanUtils to do this. Using its BeanUtils class you have access to a lot of utility methods for populating JavaBeans properties via reflection.

To copy all the common/inherited properties from a parent object to a child class object you can use its static copyProperties() method as:

BeanUtils.copyProperties(parentObj,childObject);

Note however that this is a heavy operation.




回答2:


change 'this' to 'super' in your child constructor, and remove the parent parameter, instead replace that with the two parameters int parameter1;//...int parameter1000; :)

class Parent{
public int parameter1;//...
public int parameter1000;
}

class Child extends Parent
{
    public Child(int parameter1, int parameter1000)
    {
        super.parameter1 = parameter1
        super.parameter1000 = parameter1000;
    }
}



回答3:


You can use json util to do this, such as fastjson.

Child child = JSON.parseObject(JSON.toJSONString(parent), Child.class);


来源:https://stackoverflow.com/questions/47611401/how-to-cast-parent-into-child-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!