I’m trying to understand what happend when someone casts an object of one specific class to another class. I.e there are two classes
public class Aclass{
private String attribute1;
private List<String> attribute2;
//get/set methods
}
public class Bclass{
private String attribute1;
private List<int> attribute2;
//get/set methods
}
Now inside another class i have both these objects and afterwards i cast them.
public class Cclass{
Aclass aclass=new Aclass();
//returneddata is a method that returns an Aclass object that contained dta for the Aclass attributes
aclass=returneddata();
Bclass bclass=new Bclass();
bclass=Bclass.class.cast(aclass);
}
From the aforementioned class i’m taking a java.lang.ClassCastException.
The problem is that i have two classes which does not contained only two attributes each but contained both of them 20. The 16 of these atributes are common in both classes.
Moreover the returneddata method returns an object retrieved from a repository. As you can understand i want to find a way and transfer the 16 data attributes of the object Aclass to the object Bclass.
I want:
1) To find a way to rewrite the 16 common attributes data from the one object to the other
2) How the cast is working in general
Any propositions?
The fact that both classes have similar attributes does not matter. What matters is that
AclassandBclassare not related to each other: one is not a superclass of the other. If you want to share or move data between these classes, you’ll need to copy the data from one instance to another yourself.A casting example
Let’s say we have an object
Fruit fruit = new Banana();. Now if you’d need to call a method ofBananalater in the code, you can castfruitwith the cast(Banana). Why? Because you happen to know thatfruitis aBananabut the Java compiler does not know that (it thinks it’s aFruitand it could also be a different fruit). So you have to add the cast to add additional information aboutfruitand to perform the operation safely.