Unable to reduce the visibility of the inherited method using the interface

I have two files:

public interface PrintService { void print(PrintDetails details); class PrintDetails { private String printTemplate; } public interface Task { String ACTION = "print"; } } 

and

 public class A implements PrintService { void print(PrintDetails details) { System.out.println("printing: " + details); } String action = PrintService.Task.ACTION; } 

I thought the code looked fine, but I get an error in the second file for the line void print(PrintDetails details) { , which reads:

It is not possible to reduce the visibility of an inherited method from PrintService .

Can someone explain what this means to me?

+6
source share
2 answers

In the Java interface, each default method is public :

Each method declaration in the interface body is implicitly abstract, so its body is always represented by a semicolon, not a block.

Each method declaration in the body of the interface is implicitly open. [..]

In the implementation class, you are not allowed to reduce visibility or specify an access modifier:

 void print(){..} 

you specify the default access level, which has lower visibility than public .

+21
source

Make the method public in the class in which the interface is implemented, since by default each method is public and abstract.

+2
source

Source: https://habr.com/ru/post/918084/


All Articles