-->

Which is the default access specifier in Java?

2019-01-02 20:12发布

问题:

So I just started reading a Java book and wondered; which access specifier is the default one if none is specified?

回答1:

The default visibility is known as “private package” (though you can't use this explicitly), which means the field will be accessible from inside the same package to which the class belongs.

As mdma pointed out, it isn't true for interface members though, for which the default is "public".

See Java's Access Specifiers



回答2:

The default specifier depends upon context.

For classes, and interface declarations, the default is package private. This falls between protected and private, allowing only classes in the same package access. (protected is like this, but also allowing access to subclasses outside of the package.)

class MyClass   // package private
{
   int field;    // package private field

   void calc() {  // package private method

   }
}

For interface members (fields and methods), the default access is public. But note that the interface declaration itself defaults to package private.

interface MyInterface  // package private
{
   int field1;         // static final public

   void method1();     // public abstract
}

If we then have the declaration

public interface MyInterface2 extends MyInterface
{

}

Classes using MyInterface2 can then see field1 and method1 from the super interface, because they are public, even though they cannot see the declaration of MyInterface itself.



回答3:

If no access specifier is given, it's package-level access (there is no explicit specifier for this) for classes and class members. Interface methods are implicitly public.



回答4:

The default visibility (no keyword) is package which means that it will be available to every class that is located in the same package.

Interesting side note is that protected doesn't limit visibility to the subclasses but also to the other classes in the same package



回答5:

It depends on what the thing is.

  • Top-level types (that is, classes, enums, interfaces, and annotation types not declared inside another type) are package-private by default. (JLS §6.6.1)

  • In classes, all members (that means fields, methods, and nested type declarations) and constructors are package-private by default. (JLS §6.6.1)

    • When a class has no explicitly declared constructor, the compiler inserts a default zero-argument constructor which has the same access specifier as the class. (JLS §8.8.9) The default constructor is commonly misstated as always being public, but in rare cases that's not equivalent.
  • In enums, constructors are private by default. Indeed, enum contructors must be private, and it is an error to specify them as public or protected. Enum constants are always public, and do not permit any access specifier. Other members of enums are package-private by default. (JLS §8.9)

  • In interfaces and annotation types, all members (again, that means fields, methods, and nested type declarations) are public by default. Indeed, members of interfaces and annotation types must be public, and it is an error to specify them as private or protected. (JLS §9.3 to 9.5)

  • Local classes are named classes declared inside a method, constructor, or initializer block. They are scoped to the {..} block in which they are declared and do not permit any access specifier. (JLS §14.3) Using reflection, you can instantiate local classes from elsewhere, and they are package-private, although I'm not sure if that detail is in the JLS.

  • Anonymous classes are custom classes created with new which specify a class body directly in the expression. (JLS §15.9.5) Their syntax does not permit any access specifier. Using reflection, you can instantiate anonymous classes from elsewhere, and both they and their generated constructors are are package-private, although I'm not sure if that detail is in the JLS.

  • Instance and static initializer blocks do not have access specifiers at the language level (JLS §8.6 & 8.7), but static initializer blocks are implemented as a method named <clinit> (JVMS §2.9), so the method must, internally, have some access specifier. I examined classes compiled by javac and by Eclipse's compiler using a hex editor and found that both generate the method as package-private. However, you can't call <clinit>() within the language because the < and > characters are invalid in a method name, and the reflection methods are hardwired to deny its existence, so effectively its access specifier is no access. The method can only be called by the VM, during class initialization. Instance initializer blocks are not compiled as separate methods; their code is copied into each constructor, so they can't be accessed individually, even by reflection.



回答6:

See here for more details. The default is none of private/public/protected, but a completely different access specification. It's not widely used, and I prefer to be much more specific in my access definitions.



回答7:

the default access specifier is package.Classes can access the members of other classes in the same package.but outside the package it appears as private



回答8:

Here is a quote about package level visibility from an interview with James Gosling, the creator of Java:

Bill Venners: Java has four access levels. The default is package. I have always wondered if making package access default was convenient because the three keywords that people from C++ already knew about were private, protected, and public. Or if you had some particular reason that you felt package access should be the default.

James Gosling: A package is generally a set of things that are kind of written together. So generically I could have done one of two things. One was force you always to put in a keyword that gives you the domain. Or I could have had a default value. And then the question is, what makes a sensible default? And I tend to go for what is the least dangerous thing.

So public would have been a really bad thing to make the default. Private would probably have been a bad thing to make a default, if only because people actually don't write private methods that often. And same thing with protected. And in looking at a bunch of code that I had, I decided that the most common thing that was reasonably safe was in the package. And C++ didn't have a keyword for that, because they didn't have a notion of packages.

But I liked it rather than the friends notion, because with friends you kind of have to enumerate who all of your friends are, and so if you add a new class to a package, then you generally end up having to go to all of the classes in that package and update their friends, which I had always found to be a complete pain in the butt.

But the friends list itself causes sort of a versioning problem. And so there was this notion of a friendly class. And the nice thing that I was making that the default -- I'll solve the problem so what should the keyword be?

For a while there actually was a friendly keyword. But because all the others start with "P," it was "phriendly" with a "PH." But that was only in there for maybe a day.

http://www.artima.com/intv/gosling2P.html



回答9:

Update Java 8 usage of default keyword: As many others have noted The default visibility (no keyword)

the field will be accessible from inside the same package to which the class belongs.

Not to be confused with the new Java 8 feature (Default Methods) that allows an interface to provide an implementation when its labeled with the default keyword.

See: Access modifiers



回答10:

There is an access modifier called "default" in JAVA, which allows direct instance creation of that entity only within that package.

Here is a useful link:

Java Access Modifiers/Specifiers



回答11:

Public is a keyword that is used as an access modifier for methods and variables. A variable (field) or a method declared as public is visible to and may be accessed by all classes defined in different packages.

The public keyword is used in many object-oriented programming languages (OOPL), including C++, Java, C# and Visual Basic.NET (VB.NET). A public member is loosely bound to a class and less restrictive than a private member. Variables or fields that are declared public have no accessibility restrictions. A private member, however, is only visible in its class.

public access modifier Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.

Others access modifiers

  1. private
  2. protected
  3. default

The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.

The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.

Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface. Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.

In Java, what if class as no modifier?

If a class do not have any access modifier it will be treated under default access modifier.

In object oriented programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:

A language mechanism for restricting direct access to some of the object's components A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

//Java program to illustrate default modifier
package p1;

//Class Geeks is having Default access modifier
class Geek
{
    void display()
       {
           System.out.println("Hello World!");
       }
}

..

//Java program to illustrate error while 
//using class from different package with
//default modifier
package p2;
import p1.*;

//This class is having default access modifier
class GeekNew
{
    public static void main(String args[])
       {  
          //accessing class Geek from package p1
          Geeks obj = new Geek();

          obj.display();
       }
}

..

 //Java program to illustrate error while 
//using class from different package with
//private modifier
package p1;

class A
{
   private void display()
    {
        System.out.println("GeeksforGeeks");
    }
}

class B
{
   public static void main(String args[])
      {
          A obj = new A();
          //trying to access private method of another class
          obj.display();
      }
}

..

 //Java program to illustrate
    //protected modifier
    package p1;

//Class A
public class A
{
   protected void display()
    {
        System.out.println("GeeksforGeeks");
    }
}


    //Java program to illustrate
    //protected modifier
    package p2;
    import p1.*; //importing all classes in package p1

    //Class B is subclass of A
    class B extends A
    {
       public static void main(String args[])
       {  
           B obj = new B();  
           obj.display();  
       }  

    }

..

//Java program to illustrate
//public modifier
package p1;
public class A
{
   public void display()
      {
          System.out.println("GeeksforGeeks");
      }
}
package p2;
import p1.*;
class B
{
    public static void main(String args[])
      {
          A obj = new A;
          obj.display();
      }
}

https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)
https://www.quora.com/In-Java-what-is-the-difference-between-public-class-and-class https://www.techopedia.com/definition/24018/public-java
https://www.geeksforgeeks.org/access-modifiers-java/



回答12:

First of all let me say one thing there is no such term as "Access specifier" in java. We should call everything as "Modifiers". As we know that final, static, synchronised, volatile.... are called as modifiers, even Public, private, protected, default, abstract should also be called as modifiers . Default is such a modifiers where physical existence is not there but no modifiers is placed then it should be treated as default modifiers.

To justify this take one example:

public class Simple{  
    public static void main(String args[]){  
     System.out.println("Hello Java");  
    }  
}  

Output will be: Hello Java

Now change public to private and see what compiler error you get: It says "Modifier private is not allowed here" What conclusion is someone can be wrong or some tutorial can be wrong but compiler cannot be wrong. So we can say there is no term access specifier in java everything is modifiers.



标签: