Protected method in interface [duplicate]

房东的猫 提交于 2019-12-12 02:49:28

问题


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

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

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)

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

Example code:

package Base;

public interface MilestoneAchievable {

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

Project class :

package Base;
public class Project implements MilestoneAchievable{

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

回答1:


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.




回答2:


Just do not make your interface public

or rather do 2 interfaces :

A public one

public interface MilestoneAchievable {
    public Milestone getMaxMilestone();
}

a package one

interface MilestoneAchievableProt extends MilestoneAchievable {
    void addAchievedMilestone(Milestone m) throws Exception;
}


来源:https://stackoverflow.com/questions/36422623/protected-method-in-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!