I have an external API (I can’t modify it) with class “A” and local class “B” which overrides methods of “A” and adds an additional function.
I need to use one of them according to some parameter “is_A”.
/—— API (A.java) —–/
package A;
public class A {
public int pingA( int value ) {
return value;
}
}
/—— my class (B.java) —–/
package B;
import A.*;
public class B extends A {
@Override
public int pingA( int value ) {
return value;
}
public int pingB( int value ) {
return value;
}
public static void main(String[] args) {
final boolean is_A = false;
A obj;
if (is_A) {
obj = new A();
} else {
obj = new B();
}
if (!is_A) {
int n = obj.pingB(3);
}
}
}
In this case I want to use class “B”, but the command “int n = obj.pingB(3);” is not compiled because there is no method pingB in A.
The exact message is:
cannot find symbol
symbol: method pingB(int)
location: class A.A
You need to cast
objback toB.You can by the way better use the
instanceofkeyword instead ofis_A.