Let's take a step back and understand what happens when you create an instance of the ChildClass
. A memory location is made to store the fields of ChildClass
and SuperClass
. Now you cannot make that memory location "forget" the ChildClass
fields and retain only the SuperClass
fields. The best you can do is make the ChildClass
fields null
.
So to do what you want, you'll have a create a new object. You can do so by using a method like this:
public class ChildClass extends SuperClass {
private String c;
private String d;
public SuperClass getSuperClassInstance() {
SuperClass sc = new SuperClass();
sc.a = this.a; //or use getters/setters
sc.b = this.b; //you might need to deep clone objects
return sc;
}
}
As @ruakh said, merely casting to SuperClass
is not enough as the data can be retrieved by casting it back to ChildClass
as long as it is pointing to the same memory location.
Update based on comments
So this is an XY problem!
You can annotate the fields in your child class by @JsonIgnore
or do it at class level using @JsonIgnoreProperties(value = { "c", "d" })
.
Also, the answer in this duplicate question should help.
If you need to serialize those fields in some other case, you can use JSON Views.