Reputation: 1149
I am trying to cast a child to a sibling in Java (though I'm not sure if this is allowed). Basically what is written below:
public interface BaseInterface {
public int a = 5;
}
public class ClassA implements BaseInterface {
public int a = 3;
}
public class ClassB implements BaseInterface {}
public static void main(String[] args) {
BaseInterface a = new ClassA();
ClassB b = (ClassB) a;
}
I keep getting a ClassCastException. I am trying to copy all member variables from the BaseInterface object a to b. Can someone provide a solution on how to do this? Thanks!
Upvotes: 1
Views: 4249
Reputation: 4891
public interface BaseInterface {
public int getA();
}
public class ClassA implements BaseInterface {
private final int a;
public ClassA(int a) {
this.a = a;
}
public int getA() {
return a;
}
}
public class ClassB implements BaseInterface {
private final int a;
public ClassB(BaseInterface baseInterface) {
this.a = baseInterface.getA();
}
public int getA() {
return a;
}
}
public static void main(String[] args) {
BaseInterface a = new ClassA(5);
ClassB b = new ClassB(a);
}
Will do what you want. As others noted, casting will always give a ClassCastException
.
Upvotes: -1
Reputation: 55213
This is not possible. Instead, you should give ClassA
and ClassB
copy constructors taking a BaseInterface
:
public class ClassB implements BaseInterface {
public ClassB(BaseInterface other) {
//copy state from other instance
}
}
public static void main(String[] args) {
BaseInterface a = new ClassA();
ClassB b = new ClassB(a);
}
Of course this means you're copying to a new object instead of converting, but it's the only option if you want to go from a ClassA
to a ClassB
.
Upvotes: 3
Reputation: 359796
A ClassA
is not a ClassB
, so of course this is not allowed. Even if you suppress all warnings/errors and get the code to compile, at runtime the cast will cause a ClassCastException
.
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Upvotes: 0