覆盖Java方法 [英] Overriding a Java Method
问题描述
我是Java的新手,并且已经阅读了一些有关重写方法的教程,但是我正在查看的示例无法按我预期的方式工作.例如,我有以下代码:
I'm new to Java, and I've read over some tutorials on overriding methods, but an example I'm looking at isn't working the way I expect. For example, I have the code:
public class A{
public void show(){
System.out.println("A");
}
public void run(){
show();
}
public static void main( String[] arg ) {
new A().run();
}
}
public class B extends A{
@Override
public void show(){
System.out.println("B");
}
}
当我实例化并调用B.run()时,我希望看到输出"B".但是,我看到的是"A".我在做什么错了?
When I instantiate and call B.run(), I would expect to see "B" outputted. However, I see "A" instead. What am I doing wrong?
是的,这些类位于两个单独的文件中.为了简洁起见,将它们一起显示.
Yes, the classes are in two separate files. They're shown together for brevity.
我不确定B是如何实例化的,因为它是由第三方程序使用类加载器完成的.
I'm not sure how B is being instantiated, as it's being done by a third-party program using a classloader.
有关第三方程序的更多信息.首先调用A.main(),我最初没有显示(抱歉).我假设我需要制作"new A().run();"更通用的使用当前类的名称.有可能吗?
More info on the third-party program. It starts by calling A.main(), which I didn't initially show (sorry). I'm assuming I need to make "new A().run();" more generic to use the name of the current class. Is that possible?
推荐答案
如果您执行以下操作,该代码将输出B
:
That code will output B
if you:
(new B()).run();
无论出什么问题,它都不会出现在您引用的代码中.
Whatever the problem is, it's not in the code you've quoted.
已更新(在您修改之后)
如果第三方程序正在调用A.main()
,则您无法在B
中做任何(合理的事情)将自身注入A
的操作.只要A.main
在做new A().run()
,它将有一个A
实例,而不是B
实例.没有要使用的当前类名",或者如果有(取决于您的观点),则为A
,而不是B
.
If the third-party program is calling A.main()
, there's nothing (reasonable) you can do in B
that will inject itself into A
. As long as A.main
is doing new A().run()
, it's going to have an instance of A
, not an instance of B
. There's no "current class name" to use, or if there is (depends on your point of view), it's A
, not B
.
您必须让第三方程序以某种方式而不是A
来调用B
,或者直接修改A
(例如,完全摆脱B
).您不要修改A
以使其使用B
;紧紧地将它与后代绑定在一起,使它们之间的分离变得毫无意义.
You'll have to get the third-party program to call B
in some way, rather than A
, or just modify A
directly (e.g., getting rid of B
entirely). You do not want to modify A
to make it use B
; that tightly binds it to a descendant and makes the separation between them largely pointless.
希望有帮助.
这篇关于覆盖Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!