search
HomeJavajavaTutorialThings to note when using access modifiers for Java functions

Java function access permission modifiers include: public, protected, default and private. The following precautions need to be followed: Nested classes can only access private members of external classes; functions in subclasses inherit the access permissions of the parent class, but cannot reduce them; under polymorphism, when subclasses override parent class functions, access permissions cannot be more restrictive. The ;default modifier makes the function visible only within the same package.

Java 函数的访问权限修饰符之使用时的注意事项

Access modifiers for Java functions: Precautions when using them

Preface

Access modifiers are used to control the visibility of Java functions to other classes or packages, which is crucial to ensuring the encapsulation and security of the code. This article will introduce the precautions for using function access permission modifiers in Java and illustrate them through practical cases.

Access permission modifiers

Commonly used function access permission modifiers in Java include:

  • public: Accessible anywhere
  • protected: Accessible within the same package or its subclasses
  • default (package-private): Only accessible Access
  • private within the same package: Can only be accessed within the class in which they are defined

Notes

When using the access permission modifier, you need to follow the following precautions:

  • Nested classes: Functions defined in nested classes can only access the private properties of their outer classes member.
  • Subclass: The functions in the subclass inherit the access rights of the parent class, but cannot reduce the access rights of the parent class.
  • Polymorphism: Subclasses can override functions of the parent class, but the access permissions of the overridden functions cannot be more restrictive than the access permissions of the parent class functions.
  • Package visibility: The default modifier can also be called package visibility, which means that the function is only visible in classes in the same package.

Practical case

Demonstrates a code example containing two classes to illustrate the use of access permission modifiers:

// 外部类
public class OuterClass {
    private int privateField;  // 私有字段
    protected int protectedField;  // 受保护字段
    int defaultField;  // 默认字段
    public int publicField;  // 公共字段

    // 私有方法
    private void privateMethod() {
        System.out.println("私有方法");
    }
    // 受保护方法
    protected void protectedMethod() {
        System.out.println("受保护方法");
    }
    // 默认方法
    void defaultMethod() {
        System.out.println("默认方法");
    }
    // 公共方法
    public void publicMethod() {
        System.out.println("公共方法");
    }
}

// 内部类
class InnerClass {
    public static void main(String[] args) {
        OuterClass outer = new OuterClass();

        // 访问内部类中的公共字段
        System.out.println(outer.publicField);

        // 访问外部类中的默认字段(因为内部类和外部类在同一包中)
        System.out.println(outer.defaultField);

        // 无法访问外部类中的私有字段
        // System.out.println(outer.privateField);

        // 无法访问外部类中的受保护字段(因为内部类不是外部类的子类)
        // System.out.println(outer.protectedField);

        // 无法调用外部类中的私有方法
        // outer.privateMethod();

        // 可以调用外部类中的受保护方法
        outer.protectedMethod();

        // 可以调用外部类中的默认方法
        outer.defaultMethod();

        // 可以调用外部类中的公共方法
        outer.publicMethod();
    }
}

In this In the example:

privateField
    in
  • OuterClass can only be accessed in OuterClass.
  • protectedField
  • in OuterClass can be accessed in OuterClass and its subclasses. The
  • defaultField
  • in OuterClass can be accessed from any class in the same package.
  • publicField
  • in OuterClass can be accessed from anywhere.
  • InnerClass Can access public, protected, and default members in OuterClass, but not private members.

The above is the detailed content of Things to note when using access modifiers for Java functions. For more information, please follow other related articles on 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 does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

How does platform independence simplify deployment of Java applications?How does platform independence simplify deployment of Java applications?May 02, 2025 am 12:15 AM

Java'splatformindependenceallowsapplicationstorunonanyoperatingsystemwithaJVM.1)Singlecodebase:writeandcompileonceforallplatforms.2)Easyupdates:updatebytecodeforsimultaneousdeployment.3)Testingefficiency:testononeplatformforuniversalbehavior.4)Scalab

How has Java's platform independence evolved over time?How has Java's platform independence evolved over time?May 02, 2025 am 12:12 AM

Java's platform independence is continuously enhanced through technologies such as JVM, JIT compilation, standardization, generics, lambda expressions and ProjectPanama. Since the 1990s, Java has evolved from basic JVM to high-performance modern JVM, ensuring consistency and efficiency of code across different platforms.

What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.