接口中的受保护方法 [英] Protected method in interface

查看:144
本文介绍了接口中的受保护方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口和2个实现此接口的类。请参阅下面的代码作为示例。

I have an interface and 2 classes that implement this interface. See the code below as example.

addAchievedMilestone是一个需要在每个类中实现的方法,但只能由同一个包中的类执行。

addAchievedMilestone is a method that needs to be implemented in every class, but can only be executed by a class in the same package.

为什么方法addAchievedMilestone不能受到保护?

Why can't the method addAchievedMilestone be protected?

我希望它受到保护,因此只能使用它按同一个包中的类。
(该方法不会被任何其他类扩展)

I want it to be protected so it can only be used by classes in the same package. (The method won't be extended by any other class)

但是Project-class中的修饰符总是需要公开,我该如何解决这个?

But the modifier in the Project-class always needs to be public, how can I solve this?

示例代码:

package Base;

public interface MilestoneAchievable {

    public Milestone getMaxMilestone();
    void addAchievedMilestone(Milestone m) throws Exception;
}

项目类:

package Base;
public class Project implements MilestoneAchievable{

    public Milestone getMaxMilestone() {
        //implementation goes here
    }
     public void addAchievedMilestone(Milestone m) throws Exception
    {
    //implementation goes here
    }
}


推荐答案

接口中声明的任何方法都是公共的。
子类不能降低方法的可见性/访问权限。
请参阅为什么你不能降低Java子类中方法的可见性吗?
了解详情。

Any method declared in an interface is public. And sub classes cannot reduce visibility/access of a method. See Why can't you reduce the visibility of a method in a Java subclass? for details.

这篇关于接口中的受保护方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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