为什么继承类静态方法而不是接口静态方法? [英] Why are class static methods inherited but not interface static methods?

查看:425
本文介绍了为什么继承类静态方法而不是接口静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Java中,静态方法就像实例方法一样继承,不同之处在于重新声明它们时,父实现是隐藏的而不是被覆盖。好吧,这很有道理。但是, Java教程指出

I understand that in Java static methods are inherited just like instance methods, with the difference that when they are redeclared, the parent implementations are hidden rather than overridden. Fine, this makes sense. However, the Java tutorial notes that


接口中的静态方法永远不会被继承。

为什么?常规方法和接口静态方法之间有什么区别?

Why? What's the difference between regular and interface static methods?

当我说静态方法可以继承时,让我澄清一下我的意思:

Let me clarify what I mean when I say static methods can be inherited:

class Animal {
    public static void identify() {
        System.out.println("This is an animal");
    }
}
class Cat extends Animal {}

public static void main(String[] args) {
    Animal.identify();
    Cat.identify(); // This compiles, even though it is not redefined in Cat.
}

然而,

interface Animal {
    public static void identify() {
        System.out.println("This is an animal");
    }
}
class Cat implements Animal {}

public static void main(String[] args) {
    Animal.identify();
    Cat.identify(); // This does not compile, because interface static methods do not inherit. (Why?)
}


推荐答案

这是我的猜测。

由于 Cat 只能扩展一个类,如果 Cat 扩展 动物然后 Cat.identify 只有一个含义。 Cat 可以实现多个接口,每个接口都可以具有静态实现。因此,编译器不知道选择哪一个?

Since Cat can only extend one class if Cat extends Animal then Cat.identify has only one meaning. Cat can implement multiple interfaces each of which can have a static implementation. Therefore, the compiler would not know which one to choose?

然而,正如作者所指出的,

However, as pointed out by the author,


Java已经存在此问题,使用默认方法。如果两个接口
声明默认的void identify(),使用哪一个?这是一个编译
错误,你必须实现一个重写方法(可以
只是Animal.super.identify())。所以Java已经解决了这个
的默认方法问题 - 为什么不解决静态方法?

Java already has this problem, with default methods. If two interfaces declare default void identify(), which one is used? It's a compile error, and you have to implement an overriding method (which could just be Animal.super.identify()). So Java already resolves this problem for default methods – why not for static methods?

如果我再次猜测,我会说默认,实现是 Cat 的vtable的一部分。使用 static 它不可能。主要功能必须绑定到某些东西。编译时 Cat.identify 可以被编译器替换为 Animal.identify ,但代码与现实不符如果重新编译 Cat ,但不包含包含main的类。

If I was to guess again, I'd say that with default the implementation is part of Cat's vtable. With static it cannot be. The main function must bind to something. At compile time Cat.identify could be replaced with Animal.identify by the compiler but the code wouldn't match reality if Cat was recompiled but not the class that contains main.

这篇关于为什么继承类静态方法而不是接口静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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