public methods in package-private classes

后端 未结 7 1648
刺人心
刺人心 2020-12-04 19:35

Does it make a difference to mark methods as public in package-private classes?

class SomePackagePrivateClass
{
    void foo();          // pack         


        
7条回答
  •  孤城傲影
    2020-12-04 19:48

    Well... i had this doubt also (that's why i searched for this thread). This might be a good question.

    But ...

    After a second thought, things are really simpler than we thought.

    A package-private method, is a package-private method.

    Seems nonsense? But ...

    A package-private method, even if its class is inherited, it is still a package-private method.

    Does it make more sense now? For a more verbose explanation:

    A package-private method, even if its class is inherited by a more visible subclass, it is still a package-private method.

    If the subclass is of the same package, those package-private methods are also inherited, but they are still package-private.

    If the subclass is of the different package (of here, we need the parent class to be public, with some package-private methods), those package-private methods are not inherited (because they are not visible at all).

    A point to note, which may be the cause of this doubt, that a package-private method in a public class is not visible outside its package also.


    The above explains about the package-private method. And the case of the public-method is just the same.

    When a package-private class is inherited by a pubic subclass (of the same package, this is a must), its public methods are inherited as public methods, and thus they become public methods in a pubic class.

    In the OP example, as foo() and bar() are both in a package-private class, their visibilities are limited to package-private at this moment, until further codes are added (e.g. inheritance).

    Hope this is clear (and simple) enough.

    P.S. the Java access control table

提交回复
热议问题