Java中方法的默认范围是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/714791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:39:52  来源:igfitidea点击:

What is the default scope of a method in Java?

javascope

提问by Joe Fontana

If I type:

如果我输入:

 void doThis(){
     System.out.println("Hello Stackoverflow.");
 }

what is the default scope of doThis()?

的默认范围是doThis()什么?

Public? Protected? Private?

民众?受保护?私人的?

采纳答案by Esko Luontola

The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.

默认范围是包私有的。同一个包中的所有类都可以访问方法/字段/类。Package-private 比 protected 和 public 范围更严格,但比私有范围更宽松。

More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html

更多信息:
http: //docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html

回答by Michael Haren

The default scope is "default". It's weird--see thesereferencesfor more info.

默认范围是“默认”。这很奇怪——有关更多信息,请参阅这些参考资料

回答by user15299

Anything defined as package private can be accessed by the class itself, other classes within the same package, but not outside of the package, and not by sub-classes.

任何定义为包私有的东西都可以被类本身、同一个包内的其他类访问,但不能在包外访问,也不能被子类访问。

See this pagefor a handy table of access level modifiers...

有关访问级别修饰符的方便表,请参阅此页面...

回答by erickson

Without an access modifier, a class member is accessible throughout the package in which it's declared. You can learn more from the Java Language Specification, §6.6.

如果没有访问修饰符,类成员可以在声明它的整个包中访问。您可以从Java 语言规范第 6.6 节中了解更多信息。

Members of an interface are always publicly accessible, whether explicitly declared or not.

接口的成员总是可以公开访问的,无论是否显式声明。

回答by erickson

If you are not giving any modifier to your method then as default it will be Default modifier which has scope within package.
for more info you can refer http://wiki.answers.com/Q/What_is_default_access_specifier_in_Java

如果您没有为您的方法提供任何修饰符,那么默认情况下它将是默认修饰符,它在包内具有范围。
有关更多信息,您可以参考http://wiki.answers.com/Q/What_is_default_access_specifier_in_Java

回答by shiv

Java 8 now allows implementation of methods inside an interface itself with defaultscope (and static only).

Java 8 现在允许在具有默认范围(并且仅限静态)的接口本身内部实现方法。