【问题标题】:Java Why T is still calling default method when T extends the interfaceJava为什么在T扩展接口时T仍然调用默认方法
【发布时间】:2021-09-28 11:06:28
【问题描述】:
public class Draw<T extends Print> (Print is a interface)

其他类:

public interface Print {
    static void info(String message) {
        System.out.println("failed");
    }
 }
public class Test implements Print {
    static void info(String message) {
        System.out.println(message);
    }
}

当使用new Draw&lt;Test&gt;() 并尝试运行 T.info("Test"); 它只打印“失败”

我做错了吗?

【问题讨论】:

  • Static 明确表明你想要这种行为。

标签: java static static-methods


【解决方案1】:

静态方法不会被覆盖。你必须调用 Test.info 来调用你的方法。 静态方法位于接口上,因为它是放置它们的方便位置。这不是您可以覆盖的东西,也不是默认方法。默认方法不是静态的,你必须使用 default 关键字。

如果您想要多态,请使用实例方法,而不是静态方法。

【讨论】:

    猜你喜欢
    • 2014-05-06
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2019-08-04
    • 1970-01-01
    • 2014-06-07
    相关资源
    最近更新 更多