In Java, what happens when you have a method with an unspecified visibility keyword?

前端 未结 3 1304
萌比男神i
萌比男神i 2021-01-02 04:20

I have been working with android for a few years now, not once have I had a teacher or anyone to tell me what to do. This whole time I have wondered to myself this.

3条回答
  •  被撕碎了的回忆
    2021-01-02 04:56

    Not specifying anything has a specific meaning:

    • public - any class can access this member
    • protected - subclasses can access this member (as well as code in the same class or in the same package)
    • private - only code in the same class can access this member
    • nothing ("default" access) - only code in the same package can access this member

    Arguably the last case should have had its own keyword, but we're stuck with it now. Unless you really mean to use default visibility, it's poor form to not specify anything - did you really need package visibility for some reason, or did you just default to package visibility for everything? Best practice is to explicitly use private for non-public members unless you need one of the others.

提交回复
热议问题