search
HomeJavajavaTutorialHow to use access modifiers in Java

Access modifiers in Java are used to limit the access scope of classes, interfaces, fields and methods. They respectively represent different access control levels. There are four access modifiers in Java: public, protected, default and private.

public

public is the most open access modifier and is used to specify the public access level. Classes, interfaces, fields and methods modified by public can be accessed from anywhere.

For example, the following code defines a public class:

public class MyClass {
    // ...
}

This class can be accessed from anywhere. Additionally, if a method or field is declared public, it can be accessed from anywhere. For example:

public class MyClass {
    public String name;
    public void sayHello() {
        System.out.println("Hello, world!");
    }
}

protected

protected specifies the protected access level. Classes, fields and methods modified with protected can be accessed by other classes in this package, as well as by subclasses.

For example, the following code defines a protected class:

package mypackage;
protected class MyProtectedClass {
    // ...
}

This class can only be accessed by other classes in the mypackage package, and by subclasses that inherit MyProtectedClass. In addition, if a method or field is declared protected, it can also be accessed by other classes in the same package, as well as by subclasses that inherit this class. For example:

package mypackage;
public class MyClass {
    protected String name;
    protected void sayHello() {
        System.out.println("Hello, world!");
    }
}

The name and sayHello methods of this class can be accessed by other classes in the mypackage package, as well as by subclasses that inherit MyClass.

default

default is the default access modifier in Java, it is also called package-level private access control. If a class, interface, field, or method does not use any access modifiers, then it is the default access level. The default access level means access is only available within the same package.

For example, the following code defines a class with a default access level:

package mypackage;
class MyDefaultClass {
    // ...
}

This class can only be accessed by other classes in the mypackage package. In addition, if a method or field does not use any access modifier, then it is also the default access level. For example:

package mypackage;
public class MyClass {
    String name;
    void sayHello() {
        System.out.println("Hello, world!");
    }
}

The name and sayHello methods of this class can only be accessed by other classes in the mypackage package.

private

private is the most restrictive access modifier and is used to specify a private access level. Fields and methods modified by private can only be accessed within the class in which they are defined.

For example, the following code defines a private class:

public class MyClass {
    private String name;
    private void sayHello() {
        System.out.println("Hello, world!");
    }
}

The name and sayHello methods of this class can only be accessed inside the MyClass class.

The above is the detailed content of How to use access modifiers in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

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

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft