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

Interestingly, it does not matter if the method is a public or protected package in a class protected by the package.

class Example { public void test() {} } 

instead

 class Example { void test() {} } 

I assume that maximum visibility is set by the class. And the method can only reduce visibility, and increasing visibility has no effect.

But this is valid syntax, so maybe I controlled something?

+6
source share
3 answers

If we are a subclass of Example the public class, then code outside the package can access the test() method using an instance of the subclass 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(); } } 
+5
source

If Example implemented any interface, you will need to make it public, because you cannot reduce access in this case. All default interface methods are publicly available.

+5
source

As written, he does nothing. If it is an implementation of a subclass or interface, then it can be an implementation or override of methods declared publicly available elsewhere.

0
source

All Articles