search
HomeJavajavaTutorialDetailed explanation of access permission modifiers in Java with examples

Access permission symbol:
(1)public:
For members: any other class can access them, whether in the same package or in another package.
For classes: The same is true.
(2)friendly:
As for members, it is said that if the members of a class do not have any permission modification, then they have the default package access permissions, which are expressed as friendly. Note that

note friendly It's not a keyword in Java, it's just the way I like to express it. Other classes within the same package can access it, but

outside the package cannot. For classes in the same folder that do not use packages, Java will automatically initialize these classes as the default package belonging to the directory

, and friendly members in the classes can be called each other. For example, the following two classes are in two files

in the same folder. Although no package is introduced, they belong to the same default package.

class Sundae{
//以下两个方法缺省为friendly
Sundae(){}
Void f() {System.out.println(“Sundae.f()”);
}
public class IceCream{
public static void main(String[] args){
Sundae x = new Sundae();
x.f();
}
}

For classes: Classes in the same package can be used. In short, classes can only be declared public or friendly.
(3)private:
For members: it can only be accessed in the class to which the member belongs.

class Sundae{
   private Sundae(){}//只能在Sundae class中被调用
   Sundae(int i) {}
   static Sundae makASundae() {
   return new Sundae();
   }
   }
   public class IceCream{
   public static void main(String[] args){
   // Sundae class中构造函数Sundae()是private,
   // 所以不能用它进行初始化
   //Sundae x = new Sundae();
   Sundae y = new Sundae(1);//Sundae(int)是friendly,可以在此调用
   Sundae z = Sundae.makASundae();
   }
   }

For classes: Classes cannot be declared private.

(4)protected:
For members: classes in the same package can access (package access rights); the base class grants the access rights of members in the base class to the derived class through protected, not All classes (derived class access).

(5)default (default permission)
Classes, data members, constructors, and method members can all use default permissions, that is, do not write any keywords. The default permission is the permission in the same package. Elements with permission in the same package can only be called in the class in which they are defined and in classes in the same package.

Example: package c05.local;

import pack1.Cookie;
//注意:在这里ChocolateChip继承了类Cookie,按道理bite()方法也在
//ChocolateChip中,可以用x.bite直接调用,但是不可以的,因为类ChocolateChip
//和Cookie类不在一个包中,各自具有包访问权限,为了能够使用x.bite()必须要把
//Cookie方法的访问权限换成public或者protected,但是一旦换成public所有的人就
//可以访问了,这样达不到隐私的要求,所以设置成protected最好,既可以顺利访问,也可以
//避免外面的类调用,保护好隐私的作用
public class ChocolateChip extends Cookie {
  
  public ChocolateChip() {
   System.out.println("ChocolateChip constructor");
  }
  public static void main(String[] args) {
   ChocolateChip x = new ChocolateChip();
   x.bite(); // Can't access bite
   
  }
} ///:~
package pack1;
 
public class Cookie {
public Cookie()
{
System.out.println("Cookie constructor");
}
 
protected void bite(){System.out.println("bite");}
 
}

For classes: Classes cannot be declared as protected

For permission modification of classes, as follows There is a better explanation:

Access permissions of the Class class:
public: Can be accessed by all classes.
Default: The default can be called friendly. However, there is no friendly modifier in the Java language. This name should come from c++. The default access permissions are package-level access permissions.
        That is, if you write a class without writing the access permission modifier, then it will be the default access permission, and all classes under the same package can access it, even if the class can be instantiated
     (Of course, if this class does not have Except for the ability to instantiate, for example, the class does not provide a public constructor).

Note:
1. Each compilation unit (class file) can only have one public class
2. The name of the public class (including upper and lower case) must have the same name as its class file.
3. Public class does not need to exist in a class file (*.java).
          Scenarios where this form exists: If we write a class in a certain package, it is just to work with other classes in the same package, and
        We don’t want to write documentation to customers (not necessarily It is a real-life customer, it may be a class that calls this class), which is very troublesome to watch, and it is possible that after a period of time
it may completely change the original approach and completely abandon the old version and replace it with a brand new version .
4. Class cannot be private or protected.
5. If you do not want any objects of a certain class to be generated, you can set all constructors of the class to private. But even in this way, objects of this class can be generated, that is, the static members (properties and methods) of the class can do it.

Comprehensive example:
First.java:

package Number;
import Test.*;
  
public class Frist extends Test
{
protected String s1 = "你好";
public static void main( String[] args)
{
String s2 = "java";
//System.out.println(s1);
System.out.println(s2);
  
Frist t = new Frist();
System.out.println(t.s);
t.show();
return;
}
  
}
  
Test.java:
package Test;
  
  
public class Test 
{
protected String s = "hello test"; //可以被同包中的类访问以及子类访问,该子类可以是与包Test不同
public void show()
{
Test1 t1 = new Test1();
return;
}
  
  
}
  
class Test1
{
Test1()
{
Test t = new Test();
System.out.println(t.s);
}
}

Output:

java
hello test
hello test

More examples in Java For articles related to access permission modifiers, please pay attention to the PHP Chinese website!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment