从Java调用继承类的方法

1 投票
5 回答
1509 浏览
提问于 2025-04-15 18:36

在Python中,类的方法是可以被继承的。例如:

>>> class A:
...  @classmethod
...  def main(cls):
...   return cls()
...
>>> class B(A): pass
...
>>> b=B.main()
>>> b
<__main__.B instance at 0x00A6FA58>

那么在Java中怎么做呢?我现在有:

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.main(),让它打印"B",但显然它会打印"A",因为"new A()"是写死的。

你会怎么改"new A()",让它可以根据调用时所在的类来决定,而不是固定使用类A呢?

5 个回答

1

我能想到的唯一办法就是找到哪个地方在调用 A.main( String[] arg ),然后把它改成调用 B.main

B.main 的内容是:

   public static void main( String[] arg ) {
        new B().run();
    }

你的程序是怎么启动的?是通过批处理文件、快捷方式还是其他什么方式?有没有什么可以更改的地方?A.main 是在哪里被调用的?

1

你的类 B 没有 main 方法,而且静态方法是不会被继承的。

1

在Java中,静态方法不是classmethod,而是staticmethod。一般来说,我们无法知道静态方法是从哪个类的引用中被调用的。

撰写回答