java类,扩展外部API功能
我有一个外部 API(我无法修改它),其中包含类“A”和本地类“B”,它重写了“A”的方法并添加了附加功能。 我需要根据某个参数“is_A”使用其中之一。
/------ API (A.java) -----/
package A;
public class A {
public int pingA( int value ) {
return value;
}
}
/-------- 我的类 (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);
}
}
}
在这种情况下,我想使用类“B”,但命令“int n = obj.pingB(3);”未编译,因为 A 中没有方法 pingB。 确切的消息是:
cannot find symbol
symbol: method pingB(int)
location: class A.A
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您要在子类中添加超类中不存在的新方法。无法使用对超类的引用来调用子类中的新方法。您必须转换为子类类型才能使用新方法。
你可以这样做:
这里
B
是A
但A
不是B
所以它不会有 pingB(int) 方法。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:
Here
B
is aA
butA
is not aB
so it doesn't have the pingB(int) method.您需要 cast
obj回到<代码>B。
顺便说一下,您可以更好地使用
instanceof
关键字而不是
is_A
。You need to cast
obj
back toB
.You can by the way better use the
instanceof
keyword instead ofis_A
.您需要强制转换为派生类才能调用它的方法。通常这是通过 and
if( obj instanceof B )
完成的,但由于您已经有了一个包含该信息的布尔值,因此它看起来像这样: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:obj 仍然具有 A 类型(-> 您声明了 A obj;)->这样,类型绑定不适用于编译。
obj is still having the type A (-> you declared A obj;) -> this way the type binding does not work for compilation.