Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

public methods in package-private classes

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?

like image 908
fredoverflow Avatar asked Mar 10 '11 13:03

fredoverflow


People also ask

Can a package private class have public methods?

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

What are public methods What are private methods?

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.

Can we call public method from private method?

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.

Is private method accessible from inside all classes in the same package?

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.


2 Answers

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   } } 
like image 135
Thomas Avatar answered Oct 03 '22 16:10

Thomas


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.

like image 36
Péter Török Avatar answered Oct 03 '22 17:10

Péter Török