如何将子类中的字段分配给超类

时间:2017-05-22 21:35:43

标签: java inheritance

我有一个类,我想将其存储为数据存储区中的对象。当我这样做时,我得到一个引用,我想与该对象关联。我已经扩展了我的类来创建一个包含引用的类。但是,我想将基础对象写回数据存储区(即没有引用)。我尝试过转换为超类类型,但这会将超类对象转换为子类对象。我怀疑我的方式是错误的 - 请有人指出我正确的方向。 以下是我的代码片段,以帮助解释:

class MyClass{
    String s; //Value to be stored in datastore
    //.... other variables
}

class MyClassWithId extends MyClass{
    Integer id; //Reference to location in datastore
}

class test{
    public static void main(String[] args){
        MyClassWithId withId = new MyClassWithId();
        withId.s = "String to be stored"; //Assume that this is added to the datastore
        withId.id = 123; //... and this was the id returned.

        //Assume there has been some update.
        //I now want to store a MyClass object in the datastore
        MyClass myClass = (MyClass) withId; //myClass has fields s & id :-(
    }
}

0 个答案:

没有答案