java 接口的“不能降低继承方法的可见性”的含义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11031562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:30:55  来源:igfitidea点击:

Meaning of "Cannot reduce the visibility of the inherited method" with an interface

javainterfaceaccess-specifier

提问by Alan2

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 looks okay, but I am getting an error in the second file for the line void print(PrintDetails details) {that states:

我认为代码看起来没问题,但我在第二个文件中收到一个错误,该行void print(PrintDetails details) {指出:

Cannot reduce the visibility of the inherited method from PrintService.

无法降低从 继承的方法的可见性PrintService

Can someone explain what this means for me?

有人可以解释一下这对我意味着什么吗?

回答by Jigar Joshi

In a Java interface each method is by default public:

在 Java 接口中,默认情况下每个方法都是public

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

Every method declaration in the body of an interface is implicitly public. [..]

接口主体中的每个方法声明都是隐式抽象的,所以它的主体总是用分号表示,而不是块。

接口主体中的每个方法声明都是隐式公开的。[..]

In an implementing class you are not allowed to reduce the visibility, and by not specifying an access modifier:

在实现类中,不允许降低可见性,也不允许不指定访问修饰符:

void print(){..}

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

您正在指定访问级别default,它的可见性低于public

回答by Ravi

Make methode public in the class in which interface implement,because in interface by default every method is public and abstract.

在接口实现的类中公开方法,因为在接口中默认每个方法都是公共和抽象的。