问题
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