185

If I type:

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

what is the default scope of doThis()?

Public? Protected? Private?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Joe Fontana
  • 2,306
  • 3
  • 18
  • 18

6 Answers6

284

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.

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

Esko Luontola
  • 73,184
  • 17
  • 117
  • 128
  • 2
    "Package-default is stricter than..." – reinaldoluckman Aug 20 '11 at 17:47
  • 10
    Might also be worth mentioning that "package-private" is a good scope to use when exposing methods for external unit testing. – Gary Feb 17 '12 at 16:19
  • 1
    If this is the case, then why would it ever be necessary to make something public unless you were creating creating a library or anything from which users would be getting functionality for their code? – Daniel Aug 24 '15 at 21:51
  • 2
    @user3858162 Most non-trivial applications are organized into multiple packages, in which case public scope is needed for calling calling methods from other packages. – Esko Luontola Sep 08 '15 at 13:10
20

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 page for a handy table of access level modifiers...

user15299
  • 380
  • 1
  • 3
9

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.

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

erickson
  • 265,237
  • 58
  • 395
  • 493
6

The default scope is "default". It's weird--see these references for more info.

Michael Haren
  • 105,752
  • 40
  • 168
  • 205
2

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

shiv
  • 56
  • 4
0

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