In the following code, I pass the testmethod () method an instance of subclass A called B
Unfortunately, the signature for the method accepts superclass A, not subclass B, and I cannot change this signature because it refers to many classes.
Is there a way (without changing the signature of testmethod ()) that I can access the var2 variable from inside the testmethod () method, which 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() );
System.out.println("in testmeth->" + a2.getVar2() );
}
}
class A {
int var1 = 2;
public int getVar1() {
return var1;
}
}
class B extends A {
int var2 = 8;
public int getVar2() {
return var2;
}
source
share