What is the difference between public, protected,

2018-12-30 21:48发布

In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with inheritance?

25条回答
只靠听说
2楼-- · 2018-12-30 22:37

The difference can be found in the links already provided but which one to use usually comes down to the "Principle of Least Knowledge". Only allow the least visibility that is needed.

查看更多
若你有天会懂
3楼-- · 2018-12-30 22:40

Access modifiers are there to restrict access at several levels.

Public: It is basically as simple as you can access from any class whether that is in same package or not.

To access if you are in same package you can access directly, but if you are in another package then you can create an object of the class.

Default: It is accessible in the same package from any of the class of package.

To access you can create an object of the class. But you can not access this variable outside of the package.

Protected: you can access variables in same package as well as subclass in any other package. so basically it is default + Inherited behavior.

To access protected field defined in base class you can create object of child class.

Private: it can be access in same class.

In non-static methods you can access directly because of this reference (also in constructors)but to access in static methods you need to create object of the class.

查看更多
君临天下
4楼-- · 2018-12-30 22:40

Often times I've realized that remembering the basic concepts of any language can made possible by creating real-world analogies. Here is my analogy for understanding access modifiers in Java:

Let's assume that you're a student at a university and you have a friend who's coming to visit you over the weekend. Suppose there exists a big statue of the university's founder in the middle of the campus.

  • When you bring him to the campus, the first thing that you and your friend sees is this statue. This means that anyone who walks in the campus can look at the statue without the university's permission. This makes the statue as PUBLIC.

  • Next, you want to take your friend to your dorm, but for that you need to register him as a visitor. This means that he gets an access pass (which is the same as yours) to get into various buildings on campus. This would make his access card as PROTECTED.

  • Your friend wants to login to the campus WiFi but doesn't have the any credentials to do so. The only way he can get online is if you share your login with him. (Remember, every student who goes to the university also possesses these login credentials). This would make your login credentials as NO MODIFIER.

  • Finally, your friend wants to read your progress report for the semester which is posted on the website. However, every student has their own personal login to access this section of the campus website. This would make these credentials as PRIVATE.

Hope this helps!

查看更多
旧时光的记忆
5楼-- · 2018-12-30 22:41

The official tutorial may be of some use to you.

            │ Class │ Package │ Subclass │ Subclass │ World
            │       │         │(same pkg)│(diff pkg)│ 
────────────┼───────┼─────────┼──────────┼──────────┼────────
public      │   +   │    +    │    +     │     +    │   +     
────────────┼───────┼─────────┼──────────┼──────────┼────────
protected   │   +   │    +    │    +     │     +    │         
────────────┼───────┼─────────┼──────────┼──────────┼────────
no modifier │   +   │    +    │    +     │          │    
────────────┼───────┼─────────┼──────────┼──────────┼────────
private     │   +   │         │          │          │    

+ : accessible
blank : not accessible
查看更多
牵手、夕阳
6楼-- · 2018-12-30 22:44

In very short

  • public: accessible from everywhere.
  • protected: accessible by the classes of the same package and the subclasses residing in any package.
  • default (no modifier specified): accessible by the classes of the same package.
  • private: accessible within the same class only.
查看更多
余生无你
7楼-- · 2018-12-30 22:45

Access modifiers in Java.

Java access modifiers are used to provide access control in Java.

1. Default:

Accessible to the classes in the same package only.

For example,

// Saved in file A.java
package pack;

class A{
  void msg(){System.out.println("Hello");}
}

// Saved in file B.java
package mypack;
import pack.*;

class B{
  public static void main(String args[]){
   A obj = new A(); // Compile Time Error
   obj.msg(); // Compile Time Error
  }
}

This access is more restricted than public and protected, but less restricted than private.

2. Public

Can be accessed from anywhere. (Global Access)

For example,

// Saved in file A.java

package pack;
public class A{
  public void msg(){System.out.println("Hello");}
}

// Saved in file B.java

package mypack;
import pack.*;

class B{
  public static void main(String args[]){
    A obj = new A();
    obj.msg();
  }
}

Output:Hello

3. Private

Accessible only inside the same class.

If you try to access private members on one class in another will throw compile error. For example,

class A{
  private int data = 40;
  private void msg(){System.out.println("Hello java");}
}

public class Simple{
  public static void main(String args[]){
    A obj = new A();
    System.out.println(obj.data); // Compile Time Error
    obj.msg(); // Compile Time Error
  }
}

4. Protected

Accessible only to the classes in the same package and to the subclasses

For example,

// Saved in file A.java
package pack;
public class A{
  protected void msg(){System.out.println("Hello");}
}

// Saved in file B.java
package mypack;
import pack.*;

class B extends A{
  public static void main(String args[]){
    B obj = new B();
    obj.msg();
  }
}

Output: Hello

Enter image description here

查看更多
登录 后发表回答