In the following code, I pass to the method "testmethod() an instantiation of a subclass of A, named B
Unfortunately, the signature for the method accepts the superclass A not the subclass B and I can't change that signature since it's referred by many classes.
Is there a way (without changing the signature of testmethod()) that I can access the var2 variable from within testmethod() that is part of the object that was passed to testmethod?
public class test5 {
public static void main(String args[]){
B b = new B();
testmethod(b);
}
public static void testmethod(A a2 ) {
System.out.println("in testmeth->" + a2.getVar1() ); // WORKS
System.out.println("in testmeth->" + a2.getVar2() ); // DOESNT WORK
}
}
class A {
int var1 = 2;
public int getVar1() {
return var1;
}
}
class B extends A {
int var2 = 8;
public int getVar2() {
return var2;
}
You can cast like this:
if(a2 instanceof B)
System.out.println("in testmeth->" + ((B) a2).getVar2() );
else
System.out.println("in testmeth->" + a2.getVar1() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With