Java接口覆盖方法

huangapple go评论71阅读模式
英文:

Java interfaces override method

问题

请解释为什么?找不到任何好的来源。

interface ABCD {
    default void print() {}
    static void print_static() {}
}

interface B extends ABCD {
    static void print() {} // 错误,为什么?
    default void print_static() {} // 可以,为什么?
}

回答:
@AdolisPali 因为默认方法 print 是从 ABCD 继承而来的,所以它也在接口 B 中。而且你不能在该接口中拥有一个与名称和参数相同的静态方法。

英文:

please explain why? can't find any good source

interface ABCD {
	default void print() {}
	static void print_static() {}
}

interface B extends ABCD{
	static void print() {}//error, why?
	default void print_static() {}//fine, why?
}

Answer:
@AdolisPali Becase the default method print is inherited from ABCD, so it's in interface B too. And you can't have a static method in that interface with the same name and arguments – fps

答案1

得分: 2

你不能覆盖接口的静态方法;你只能通过接口的名称访问它们。如果你试图通过在实现接口中定义类似的方法来覆盖接口的静态方法,它将被视为另一个方法。

参考链接:https://www.tutorialspoint.com/default-method-vs-static-method-in-an-interface-in-java#:~:text=You%20cannot%20override%20the%20static%20(static)%20method%20of%20the%20class.

在Java中,关键字static实际上表示该成员属于类型本身。

英文:

You cannot override the static method of the interface; you can just access them using the name of the interface. If you try to override a static method of an interface by defining a similar method in the implementing interface, it will be considered as another method.

See this: https://www.tutorialspoint.com/default-method-vs-static-method-in-an-interface-in-java#:~:text=You%20cannot%20override%20the%20static,static)%20method%20of%20the%20class.

Essentially in Java, the keyword static indicates that the particular member belongs to a type itself.

答案2

得分: 1

每个实例方法会自动继承给它们的子类,并且只能被子类中的实例方法覆盖。静态方法无法覆盖实例方法。因此在您的情况下,来自ABCD的方法"default void print_static()"不会覆盖来自B的"static void print_static()"。您仍然可以为ABCD调用print_static(),对于B调用print_static()。

英文:

Every instance method automatically inherits to their sub classes and only can be overridden by instance method from their sub classes too. Static method can not override instance method. Thus in your case, method "default void print_static()" from ABCD doesn't override "static void print_static()" from B. You still can call ABCD.print_static() for ABCD and print_static() for B.

huangapple
  • 本文由 发表于 2020年9月24日 01:09:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64033008.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定