tangens
tangens

Reputation: 39733

Is there any reason for public methods in a package protected class?

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?

Upvotes: 11

Views: 3013

Answers (3)

AllTooSir
AllTooSir

Reputation: 49372

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();
  }
}

Upvotes: 8

Adrian
Adrian

Reputation: 46433

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.

Upvotes: 0

duffymo
duffymo

Reputation: 308743

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.

Upvotes: 7

Related Questions