public methods in package-private classes

If the class is not going to be extended by another, more visible subclass*, the only difference is clarity of intent. Declaring all methods package private makes it more difficult for future readers to determine which of the methods are meant to be called by other classes in the same package.

*which would not make much sense as a design solution to me, but technically is possible nevertheless.


Another case where the method has to be public is when you are creating a package private implementation of some public class or interface. Since you are not allowed to reduce the visibility of overridden methods, these have to be public.


Example using inheritance:

A.java

package pkg1

class A {
  void foo();
  public void bar() {};
}

B.java

package pkg1

public class B extends A{

}

C.java

package pkg2

public class C {
  public void doSomething() {
   B b = new B();
   b.bar(); //ok
   b.foo(); //won't work, since foo() is not visible outside of package 'pkg1'

   A a = new A(); //won't work since A is not visible outside of package 'pkg1'
   a.bar(); //won't work, since a cannot be created
  }
}