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
}
}
Yes. Well, obviously you can access those methods from within the same class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With