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

3
  • check this stackoverflow.com/a/36964366/8813998 Commented Apr 25, 2020 at 8: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); Commented Apr 25, 2020 at 8: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: stackoverflow.com/a/21613593/11377112 Commented Apr 25, 2020 at 8:49

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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: stackoverflow.com/a/21613593/11377112

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.