我有一个接口(interface)和两个实现该接口(interface)的类。请参阅下面的代码作为示例。
addAchievedMilestone是每个类都需要实现的方法,但只能由同一个包中的类执行。
为什么addAchievedMilestone方法不能被保护?
我希望它受到保护,因此它只能由同一包中的类使用。 (该方法不会被任何其他类扩展)
但是Project类中的修饰符总是需要公开,我该如何解决这个问题?
示例代码:
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
}
}
最佳答案
接口(interface)中声明的任何方法都是公共(public)的。 并且子类不能减少方法的可见性/访问。 请参阅Why can't you reduce the visibility of a method in a Java subclass? 了解详情。
关于java - 接口(interface)中的 protected 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36422623/