public methods in package-private classes

Solution 1:

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
  }
}

Solution 2:

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.

Solution 3:

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.

Solution 4:

It makes very little difference, unless the class is extended by a public (or protected nested) class.

As a matter of consistency, I'd go for public. It should be rare for methods to be anything other than public or private.

There are a number of examples of public methods in the package private java.lang.AbstractStringBuilder class. For instance length() is public in AbstractStringBuilder and is exposed in the public class StringBuilder (overridden in StringBuffer to add synchronisation).