views:

92

answers:

4

Hello, 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

Please advise.

+7  A: 

You're adding a new method in a subclass which does not exist in the super class. There is no way to call the new method in the subclass using a reference to the superclass. You'd have to cast to to the subclass type to use the new method.

You could do something like:

A obj = new B();

if (obj instance of B) {
   B b = (B)obj;
   int n = b.pingB(3);
}

Here B is a A but A is not a B so it doesn't have the pingB(int) method.

Jeremy Raymond
+1  A: 

You need to cast obj back to B.

if (!is_A) {
    int n = ((B) obj).pingB(3);
}

You can by the way better use the instanceof keyword instead of is_A.

if (obj instanceof B) {
    int n = ((B) obj).pingB(3);
}
BalusC
Thanks a lot, this works.Should this approach (I mean casting) affect the processing speed?
Serg
No, certainly not.
BalusC
A: 

obj is still having the type A (-> you declared A obj;) -> this way the type binding does not work for compilation.

manuel aldana
+1  A: 

You need to cast to your derived class to be able to call it's methods. Usually that is done with and if( obj instanceof B ) but as you already have a boolean with that information it's going to look like this:

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 = ((B) obj).pingB(3); 
    } 
}
x4u