为什么 class Cougar 需要在第 5 行实现方法的 public 版本,而它在这一行没有方法(关于重载)

Why the class Cougar needs to implement a public version of the method at line 5 when it does not have a method at this line( about overload)

我明白 "the method getTailLength() in the interface Hastail is assumed to be public, since it is part of an interface, therefore, the implementation of the method on line 3 protected int getTailLength() {return 4;} is an invalid override"。

但我不知道为什么第5行不正确。解释说"the class Cougar implement an overloaded version of getTailLength(),but since the declaration in the parent class Puma is invalid, it needs to implement a public version of the method"。

这一行不包含getTailLength()方法,为什么需要实现public版本的方法?

抱歉这个愚蠢的问题,我正在尽力理解它。

interface HasTail { int getTailLength(); }
abstract class Puma implements HasTail {
 protected int getTailLength() {return 4;}
}
public class Cougar extends Puma {
 public static void main (String[] args) {
 Puma puma = new Puma();
 System.out.println(puma.getTailLength());
}
public int getTailLength(int Length); {return 2;}  
}

因为你无法将方法签名从public更改为protected仍然实现public 来自 HasTail 的界面。在Java 8+中,也可以为接口提供一个default方法体。

您的代码格式不正确,因此,您遗漏了一个错误:这个分号让您感到困惑:

public int getTailLength(int Length); {return 2;}  

正确格式Java中,这相当于:

public int getTailLength(int Length) {
     // empty method
}; 


{
    return 2;
}  

代码格式很重要,不要马虎,为了你也为了我们。