开发者

java class, extending external API functionality

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( i开发者_JS百科nt 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'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.


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜