较低可见性的覆盖方法会导致编译错误 [英] Overriding method with a lower-visibility one results in compilation error

查看:81
本文介绍了较低可见性的覆盖方法会导致编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类和一个接口:

I have one class and one interface:

public interface A {
    public void getNum();
}

public class B {
    public void getNum() {
        System.out.println("4");
    }
}

public class C extends B implements A {
    protected void getNum() {
        System.out.println("3");
    }
}

现在我的问题是,为什么这段代码会给出编译错误,以及如何避免它.有什么方法可以在类C中重写此方法?

Now my question is, why this code is giving compilation error and how can we avoid it. Is there any way in which we can override this method in class C?

推荐答案

来自Java语言规范:

From Java Language Specification:

jls-8.4 .8.3

覆盖或隐藏方法的访问修饰符(第6.6节)必须至少提供与覆盖或隐藏方法相同的访问权限,如下所示:

The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:

  • 如果覆盖或隐藏方法是公共的,则覆盖或隐藏方法必须是公共的;否则,将发生编译时错误.
  • ...

请注意,您正在尝试使用具有protected访问修饰符的新方法覆盖从类B(以及从接口A)继承的public方法getNum().这意味着您正在尝试降低此方法的可见性,根据规范,此方法不正确.
为了能够覆盖此方法,您需要在该方法的新版本中使用public访问修饰符.

Notice that you are trying to override public method getNum() inherited from class B (and also from interface A) with new one that has protected access modifier. It means that you are trying to reduce visibility of this method which according to specification is incorrect.
To be able to override this method you need to use public access modifier with your new version of that method.

为什么您不能降低能见度?看一下下面的代码,该代码使用您的类,但放在其他软件包中,并问自己此代码应如何表现?".

Why you cant reduce visibility? Take a look at below code which uses your classes but is placed inside some other package and ask yourself "how should this code behave?".

package my.pckage;

import your.pckage.A;
import your.pckage.C;

public class Test{
    public static void main (String[] args){
        C C = new C();
        c.getNum();// ERROR: Test class doesn't have access to `c`s protected method.
                   // Why should it have, Test doesn't extend C.

        A a = (A)c;// Lets try using other reference
        a.getNum();// Should `a` have access to method that is protected in `C`?
                   // If yes, then what is the point of declaring this method 
                   // protected if all I would have to do to get access to it is 
                   // casting instance of C to A interface?
    }
}

这篇关于较低可见性的覆盖方法会导致编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆