How java casting work, is it change the state of Object or create new Object?
I have a method dummy with A as class parameter, but i need to pass
instance of subclasses B to that method. I know from: Does Java casting
introduce overhead? Why? that downcasting in java have overhead. Most of
my code deal with subclass B so i dont use downcasting for this purpose.
Instead i use temporal instance variable cc for that purpose. But this is
not make a change for object of subclass m. I need change in variable cc
avaliable too for instance variable m. This is my code:
public class TestExtends {
public TestExtends() {
SubTypeA m = new SubTypeA(12, 3);
dummy(m);
MainType cc = m;
dummy(cc);
System.out.println(m.a);
System.out.println(cc.a);
}
public void dummy(MainType t) {
t.a = 22222;
}
public static void main(String[] args) {
new TestExtends();
}
}
class MainType {
public int a = 0;
public MainType(int a) {
this.a = a;
}
}
class SubTypeA extends MainType {
public int a;
public int b;
public SubTypeA(int a, int b) {
super(a);
this.a = a;
this.b = b;
}
}
with output
12
22222
No comments:
Post a Comment