简体   繁体   中英

Why does java force all interface members to be public?

Suppose I have a file test.java with the following:

interface IA {
  void f();
}

class A implements IA {
  public void f() {
    System.out.println("test");
  }
}

void f() in interface IA is public by default as mentioned in the docs :

All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

This forces me to include the public modifier in my implementation of f in class A . Why does java force all implementations of interface members to be fully public ? What if I only wanted f to be accessible from my own package?

EDIT to clarify

Interfaces are by default package-private but interface members are by default public . In the code example I show above, this forces me to declare A 's implementation of f as public . But I don't see why this has to be the case. Consider the following table from the docs :

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

Why can the interface member f not be package-private or protected ? In this case the implementing class A is not in another package, but in the same package. Therefore public is too "public" for my purposes. Furthermore it breaks the rule of thumb mentioned in the docs:

Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.

Your A class has the default modifier. So you can start by reducing accessibility by the class modifier. An interface is a public contract (but interface itself does not need to have the public modifier. It can have the default modifier for example.). So, if it is a public contract and you implement it, is because you want to say to the world that you follow that contract. You can always implement a method without implementing the interface. You loose the interchange that interface allows.

So think for a second. You have class A that says it implements IA . Your class, since implements IA is used somewhere else, since follow the public contract. If you have reduced the visibility of that method what will occur? The implications of breaking the contract are too many. It's like you have a collection that implements List, and then you make all interface methods that you implement private. What happens when you try to use you class as an interface instance?

In Java you cannot reduce a method visibility when implementing an interface or extending a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM