The public accessors in the default accessor class .. what's the point?

What does it mean if you make a default access for a class and mark the method contained in the public class? In other words, how can you publish access to a method if the private class is not publicly accessible?

+3


source to share


3 answers


Keeping public methods can be useful in some cases, such as when your default access class implements a public interface.



This is useful when your API is defined in terms of interfaces and the default class is one of these public interfaces. Users of your API can instantiate the default accessor class using factory methods.

+2


source


public

often required when you override some public methods or implement interface

s.
Let's take a simple example of the Object # equals method.



Although your main class would have a default scope , you cannot override this method when the visibility is reduced. Therefore, you will need:public void equals(.......

+2


source


You mean something like this:

package p1;
class C1 {
    public void publicMethod() {}
}

      

In another package:

package p2;
import p1.C1; // not allowed
public class C2 {
    C1 c1; // not allowed
    void test() {
        c1.publicMethod(); // not allowed
    }
}

      

In case of inheritance, you can use publicMethod

:

package p1;
public class C2 extends C1 {}

      

publicMethod

Can now be accessed:

package p2;
import p1.C2; // C2 is public, ok !
public class C3 {
    C2 c2;  // C2 is public, ok !
    void test() {
        c2.publicMethod(); // C2 is public, use publicMethod of C1 !
    }
}

      

So, reduce the visibility class

that can be useful for the abtract class, which should not be used directly outside of the package.

0


source







All Articles