Java tutorial says I can have a package-private interface, but I can’t

It’s the interface itself that can be package-private, not the methods in it. You can define an interface that can only be used (by name) within the package it’s defined in, but its methods are public like all interface methods. If a class implements that interface, the methods it defines must be public. The key thing here is that it’s the interface type that isn’t visible outside the package, not the methods. The docs are not incorrect, because using the methods defined in the interface is not the same as using the interface itself.

Also be aware that when defining an interface, not adding public before a method definition doesn’t change anything since the methods are all implicitly public.

If the class(es) that you have implementing the interface are themselves package-private, the publicness of the interface methods is obviously not an issue. You could also, of course, use an abstract class instead of an interface if the single-inheritance issue doesn’t get in your way:

abstract class Whatever {
  abstract void foo();
  abstract void bar();
}

Leave a Comment