Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public members in package private class

I wonder if it's okay (not considered bad practice) to have public members in package private class. I tend to add public keyword to members of my default visibility classes to indicate that such members are part of the classes API.

I do it only for readability, since in this case public members have essentially the same visibility as members without any access modifiers (i.e. package visibility). Is that correct?

Example:

class ModuleImplementationClass {
    private int fieldA;
    private String fieldB;

    private void someClassInternalMethod() {
         // impl
    }

    public int doSth() {
        // method that will be called by other classes in the package
    }
}
like image 250
siledh Avatar asked Oct 03 '13 14:10

siledh


People also ask

Can a package private class have public methods?

Yes. Well, obviously you can access those methods from within the same class.

Can I access public members outside the package if the class is default?

Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package.

Can a private class have public members Java?

Yes, it is possible to specify public access modifier for a field in java irrespective of the access modifier of its container class. By definition public access modifier has the biggest scope. So as long as you can access your private class you will be able to access public fields within it.

What is private and public specifier related to package?

Public is a keyword denoting that that particular item can be accessed outside the package. Private means that the item will only be used internally in the package.


1 Answers

I do it only for readability, since in this case public members have essentially the same visibility as members without any access modifiers (i.e. package visibility). Is that correct?

Well that depends. Not if you're overriding existing methods (e.g. toString()) or implementing an interface.

If you don't want the method to be used from outside the package, make it package private. If you're happy for it to be used from anywhere, make it public. Or another way to think about it: design your method access so that if someone changed just the class access to make it a public class, you wouldn't want to change the method access too.

like image 199
Jon Skeet Avatar answered Oct 31 '22 21:10

Jon Skeet