0

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

d0ye
  • 1,580
  • 1
  • 15
  • 26
  • check this https://stackoverflow.com/a/36964366/8813998 – devROYAL Apr 25 '20 at 08:36
  • 3
    I'm afraid you'll have to create your own copy-constructor on the super class. Then you can do `SuperClass sup = new SuperClass(sub);` – Thilo Apr 25 '20 at 08:46
  • 1
    you can cast the object to the superclass, however the overridden methods won't behave like they were of the superclass, more info here: https://stackoverflow.com/a/21613593/11377112 – Animesh Sahu Apr 25 '20 at 08:49

1 Answers1

4

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.

jurez
  • 4,436
  • 2
  • 12
  • 20
  • This is neat and the only possible way iirc, but the overridden methods won't behave like they were of the superclass, btw +1, more info here: https://stackoverflow.com/a/21613593/11377112 – Animesh Sahu Apr 25 '20 at 08:49