Consider I have a class like below.
public class SuperClass
{
private String a;
private String b;
//getter/setters
}
And a subclass
public class ChildClass extends SuperClass
{
private String c;
private String d;
//getter/setters
}
In another class I have an object of the ChildClass. This object has both the parent and child class member variables populated with data.
Using this object, I need to get an instance of parent class, i.e, an object which only has the variables in the parent class (i.e., a and b). How can I achieve it ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With