在Java中,当您的方法具有未指定的可见性关键字时会发生什么? [英] In Java, what happens when you have a method with an unspecified visibility keyword?

查看:117
本文介绍了在Java中,当您的方法具有未指定的可见性关键字时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在android上工作了几年了,没有一次我有老师或任何人告诉我该怎么做.这整个时间我都在想这个.

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.

当您有一种方法时,我通常会看到...

When you have a method I generally see...

public void method(){
//Stuff
}

private void method(){
//stuff
}

我知道void是没有返回值的方法,而public在某种程度上是该方法的可见性,但是如果我只是使用这种方法就很重要了.

I know that a void is a method with no return value, and that public is the visibility of the method in a way but would it matter if I just used something like this...

void method(){
//stuff
}

因为那样方法可见性还是默认设置吗?

Because then the methods visibility would just be default anyway?

我不知道我是否正确,指定公开"还是私有"只是一种好习惯?

I have no idea if I am right or not, is it just good practice to specify "public" or "private" ?

推荐答案

未指定任何内容具有特定含义:

Not specifying anything has a specific meaning:

  • public -任何类都可以访问该成员
  • 受保护的-子类可以访问此成员(以及相同类或相同程序包中的代码)
  • private -只有同一个类中的代码才能访问此成员
  • 没有任何内容(默认"访问权限)-只有相同 package 中的代码才能访问该成员
  • 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

可以说,最后一种情况应该有自己的关键字,但是我们现在仍然坚持使用它.除非您真的打算使用默认可见性,否则它是不好的形式,不指定任何内容-您是否确实出于某些原因需要程序包可见性,还是只是默认情况下对所有程序都具有程序包可见性?最佳实践是对非公共成员明确使用 private ,除非您需要其他成员之一.

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.

这篇关于在Java中,当您的方法具有未指定的可见性关键字时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆