11

I wonder if it makes any difference if a method is public or package protected in a class that is package protected.

class Example {
  public void test() {}
}

instead of

class Example {
  void test() {}
}

I guess the maximum visibility is given by the class. And a method can only reduce the visibility and increasing the visibility has no effect.

But it's valid syntax, so perhaps I've overseen something?

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
tangens
  • 39,095
  • 19
  • 120
  • 139
  • Thats a good question, i know in c++ theres a combination of protected+public that makes no effect in inheritance, my guess is that here it has effect for classes in the same package. – Ariel Pinchover Apr 17 '13 at 20:11

3 Answers3

8

If we subclass Example to a public class , then code outside the package can access test() method using the subclass instance if it is public .

Example:

package A;
class Example {
   public void test() {}
}

package A;
public class SubExample extends Example {
}

package B;
import A.SubExample;
class OutsidePackage {
  public void some method(SubExample e){
    // Had test been defined with default access in class Example
    // the below line would be a compilation error.
    e.test();
  }
}
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • Can you give me an example? I can't follow you. – tangens Apr 17 '13 at 20:26
  • I tried to build an example using reflection. But I get the exception 'java.lang.IllegalAccessException: Class other.Other can not access a member of class example.Example with modifiers "public"'. So it seems that the package protection of the class protects its public methods, too. – tangens Apr 17 '13 at 21:20
  • Good example, thank you. So it really makes a difference if the member is package protected or public! – tangens Apr 18 '13 at 06:10
7

If Example implemented an interface of some kind you'd have to make them public, because you can't reduce access in that case. All interface methods are, by default, public.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • Good point. So would you always make your "package protected" methods public when the class is already package protected? – tangens Apr 17 '13 at 20:17
  • Not all. I wouldn't make constructors public, because that's the point. – duffymo Apr 17 '13 at 20:42
0

As written, it does nothing. If it's a subclass or interface implementation, then it may be implementing or overriding methods that are declared public elsewhere.

Adrian
  • 42,911
  • 6
  • 107
  • 99