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;
}