Does it make a difference to mark methods as public
in package-private classes?
class SomePackagePrivateClass { void foo(); // package private method public void bar(); // public method }
Is there any practical difference in visibility between foo
and bar
here?
Yes. Well, obviously you can access those methods from within the same class.
Public instance methods: - Use if displaying information or interacting with other classes and/or the client. Private instance methods: - Accessible only from within class scope. - Part of the class inner-workings.
If a private method must call a public method, then the content of the public method should be taken and placed in a private method, which both methods can then call.
Public methods inside a package class are public to classes in the same package. But, private methods will not be accessible by classes in the same package.
Example using inheritance:
A.java
package pkg1 class A { void foo(); public void bar() {}; }
B.java
package pkg1 public class B extends A{ }
C.java
package pkg2 public class C { public void doSomething() { B b = new B(); b.bar(); //ok b.foo(); //won't work, since foo() is not visible outside of package 'pkg1' A a = new A(); //won't work since A is not visible outside of package 'pkg1' a.bar(); //won't work, since a cannot be created } }
If the class is not going to be extended by another, more visible subclass*, the only difference is clarity of intent. Declaring all methods package private makes it more difficult for future readers to determine which of the methods are meant to be called by other classes in the same package.
*which would not make much sense as a design solution to me, but technically is possible nevertheless.
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