从Java调用继承的类方法 [英] Calling An Inherited Class Method From Java

查看:142
本文介绍了从Java调用继承的类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,类方法可以被继承.例如

In Python, class methods can be inherited. e.g.

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

您将如何使用Java进行等效操作?我目前有:

How would you do the equivalent in Java? I currently have:

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",但是显然,由于"new A()"是硬编码的,因此它将打印为"A".

I'd like to call B.main() and have it print "B", but clearly it will print "A" instead, since "new A()" is hardcoded.

您将如何更改"new A()",以便对其进行参数化以使用其在调用时所在的类,而不是硬编码的类A?

How would you change "new A()" so that it's parameterized to use the class it's in when called, and not the hard-coded class A?

推荐答案

java中的静态方法不是classmethod,而是staticmethod.通常,不可能知道从哪个类引用了静态方法.

Static methods in java are not classmethods they are staticmethods. In general it is not possible to know which class reference the static method was called from.

这篇关于从Java调用继承的类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆