0

I am trying to cast a child type to a parent type. The thing is since the child class extends parent class, when casting to the parent type child specific attributes are also kept. I would like to leave out some of the child class attributes and keep only parent class attributes.

I have found a way of doing this with GSON nevertheless, I would like to know if it is possible to do so with plain JAVA code.

Trick with GSON

JsonUtils.getGsonBuilder().fromJson(JsonUtils.getGsonBuilder().toJson(respondents.get(0),RespondentBase.class),RespondentBase.class);
Nesan Mano
  • 1,892
  • 2
  • 26
  • 43

1 Answers1

0

When you do a cast in Java code, the object you cast doesn't change at all. The only thing you're doing is to reference that object from a variable that has access only to the casted into class member variables and methods. However, the original class member variables and methods are still there and you'll always be able to use them if you reference the object using a variable of the proper type.

To put it into different words: Once you create an object, it's class, and sets of attributes and methods remain the same until it's garbage collected.

Andres
  • 10,561
  • 4
  • 45
  • 63
  • From what I understand, casting is probably a way of telling the compiler that it is safe to assume a given object as its parent type – Nesan Mano Nov 18 '19 at 22:46