Nanxi Li Nanxi Li - 6 months ago 21
Java Question

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)

I understand that "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".

But I don't know why line 5 is incorrect. The explanation says that"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".

This line does not contain the
getTailLength()
method,why it needs to implement a public version of the method?

Sorry for the stupid question, I am trying my best to understand it.

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;}
}

Answer

Because you can't change the method signature from public to protected and still implement the public interface from HasTail. In Java 8+, it is also possible to provide a default method body to the interface.