d0ye
d0ye

Reputation: 1610

Java construct a superclass instance with subclass instance

What I was trying to do is like

SuperClass super = convertToSuperClassInstance(SubClass sub);

Clearly sub could directly sign to super, But I need super should be SuperClass(remove useless subclass data), Due to other persist related things, Is there any trick I could do That?

Create new SuperClass and sign all object data to it seems no elegant to me QAQ

Upvotes: 0

Views: 60

Answers (1)

jurez
jurez

Reputation: 4657

An instance of subclass will always have all the fields and methods of a superclass. Casting the subclass to superclass (i.e. (SuperClass) subclass) will not remove the data, it will just tell the compiler to apply the rules for SuperClass, which means you will get a compile-time error if you try to access subclass' data. Nevertheless, you can still downcast it back to subclass or use reflection - the data is there. This is by design and you can't get away from it.

If you want to really "remove" the data of a subclass, you need to construct a new instance of a superclass, not subclass. The easiest way would be to add a constructor to superclass that takes a superclass as a parameter and copies all superclass-related data from it.

Upvotes: 4

Related Questions