0

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
    }
}
Programmer1994
  • 955
  • 3
  • 13
  • 29

2 Answers2

3

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.

Community
  • 1
  • 1
Yogesh_D
  • 17,656
  • 10
  • 41
  • 55
  • Project doesn't have a subclass. Protected is only used to achieve that only classes in the same package can execute the method. – Programmer1994 Apr 05 '16 at 09:52
  • 1
    What Yogesh_D is saying is that `Project` *is* a subclass. That it's a subclass of `MilestoneAchievable` and that it can't reduce visibility from public to package private. As you can see in [this table](http://stackoverflow.com/a/33627846/276052) it would indeed be a reduction in visibility. – aioobe Apr 05 '16 at 10:01
1

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;
}
Ji aSH
  • 3,206
  • 1
  • 10
  • 18
  • I'm getting an error that the modifier of the implemented addAchievedMilestone-method needs to be public... – Programmer1994 Apr 05 '16 at 09:50
  • I dont have it ^^ might be du to a difference in our java version ? By the way, puting it public will not change anything: your interface will still be package restricted :) – Ji aSH Apr 05 '16 at 11:44