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 TestCast {
public TestCast() {
B m = new B(12, 3);
dummy(m);
A cc = m;
dummy(cc);
System.out.println(m.a);
System.out.println(cc.a);
}
public void dummy(A t) {
t.a = 22222;
}
public static void main(String[] args) {
new TestCast();
}
}
class A {
public int a = 0;
public A(int a) {
this.a = a;
}
}
class B extends A {
public int a;
public int b;
public B(int a, int b) {
super(a);
this.a = a;
this.b = b;
}
}
with output
12
22222