I have upcasted Model2 instance in the following code to Object class and then downcasted back to the class - Model2 in the test method of Model1 class. But thenUov its attribute value after downcasting is showing null. Is this expected for the instance to loose its state after Upcasting-then-Downcasting? Could you please share some details for the same. Also, is there a way to retain the state of the instance after upcasting?
public class Demo{
public static void main(String[] args) {
Model1 m1 = new Model1();
m1.setAttr1(10);
Model2 m2 = new Model2();
m2.setAttr2(10);
m1.test(m2);
}
}
class Model1 {
private Integer attr1;
public Integer getAttr1() {
return attr1;
}
public void setAttr1(Integer attr1) {
this.attr1 = attr1;
}
public void test(Object o) {
Model2 m = (Model2) o;
System.out.println(m.getAttr2());
}
}
class Model2 {
private Integer attr2;
public Integer getAttr2() {
return attr2;
}
public void setAttr2(Integer attr1) {
this.attr2 = attr2;
}
}