search
HomeJavajavaTutorialAccess Modifiers in Java

As we all know, Java is one of the top programming languages in the world. Billions of devices are relying on it for the last two decades. Java is a fast, dependable, safe, and multi-platform language. Java runs on any device as long as that device has Java Runtime (JRE), making it multi-platform, fast, and dependable. Access modifier is the property of java, which makes it safe across the multi-platform. Java provides class-level safety (during encapsulation) to the programmer by using the access modifier property. According to the book, Class is the blueprint for building an object in java, which makes it a ‘Building block’ for the program as Java is an Object-Oriented language. An access modifier specifies how any class can access a given class and its fields, constructors, and methods within and different packages. Class, fields, constructors, and methods can have one of four different Java access modifiers.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • Private
  • Public
  • Protected
  • Default – No keyword required.

Different Access Modifiers in Java

The following table summarizes how we can apply Java access modifiers to the program:

Modifiers Class Packages Sub-Class World
Private Y N N N
Public Y Y Y Y
Protected Y Y Y N
Default Y Y N N

We will cover each Java access modifier in the following sections.

1. Default

When any class, data member, and variable is declared by not writing with an access modifier, then it is set to ‘default’ access modifier. The ‘default’ access modifier means the code inside any class can access the entire program within the same package.

  • This access modifier works within the same package only.
  • Sometimes, a ‘default’ access modifier is also referred to as a package access modifier, as it is accessible within the same package only.
  • Subclasses could not access methods, data members, and variables (fields) in the superclass if these methods, data members, and variables (fields) are marked with the ‘default’ access modifier in the class unless these subclasses located in the same package as the superclass.

Example #1:

//Java program to show the default modifier.
package Test;
//Where Class eduCBA is having Default access modifier as no access modifier is specified here
class eduCBA
{
void display ()
{
System.out.println("Hello World!");
}
}

Output:

Hello World!

Example #2:

//Java program to show error while using class from different package with default modifier
package test2;
import test.*;
//This class check is having default access modifier
class Check
{
public static void main(String args[])
{
//accessing class eduCBA from package test
eduCBA obj = new eduCBA();
obj.display();
}
}

Output:

Compile-time error.

2. Protected

Syntax ‘protected’ is used by users when they want to use this access modifier.

  • This access modifier is accessible only within the same package or same sub-classes in different classes (but users have to import that package where it was specified).
  • Users cannot mark class and interfaces with a ‘protected’ access modifier. However, Methods and fields can be declared as protected If methods and fields are in an interface.

For Example:

//Java program to show to protected access modifier
package test;
//Class eduCBA
public class eduCBA
{
protected void display ()
{
System.out.println("Hello World!");
}
}
//Java program to show to protected modifier in same sub-classes of different packages
package test2;
import test.*;
//Class pro is subclass of eduCBA
class pro extends eduCBA
{
public static void main(String args[])
{
pro obj = new pro();
obj.display();
}
}

Output:

Hello World!

3. Public

Users can declare a class, method, constructor, and interface with a ‘public’ access modifier, which can access by any class, method, constructor, and interface within or different packages.

  • This access modifier has the Boundless among all modifiers.
  • When any class, method, or package is marked with a ‘public’ access modifier, it is accessible to everyone from anywhere from the program.
  • There are no limitations on the scope of ‘public’ access class methods.

For Example: –

//Java program to show to public access modifier
package test;
public class eduCBA
{
public void display ()
{
System.out.println("Hello World!");
}
}
package test2;
import test.*;
class pub
{
public static void main (String args [])
{
eduCBA obj = new eduCBA ();
obj.display ();
}
}

Output:

Hello World!

4. Private

When a method or variable is marked as ‘private’ access modifiers, then code inside that same class can only access those methods and variables.

User can not declare any super-class with a ‘private’ access modifier in the program. If the user does so with any class, it makes that class not accessible to any other class in the same package, making class none of the use. However, the user can declare variables and methods within the class with a ‘private’ access modifier, so anyone cannot utilize those variables and methods.

Occasionally people got confused with ‘private’ and ‘protected’ access modifiers, but they both are different.

For Example: –

//Program to show error while using a class from different packages with private modifier.
package test;
class eduCBA
{
private void display()
{
System.out.println("Hello World!");
}
}
class Check
{
public static void main (String args[])
{
eduCBA obj = new eduCBA();
//make class check to access private method of another class eduCBA.
obj.display();
}
}

Output:

error: display() has private access in eduCBA obj.display();

Conclusion

Java access modifier gives you an extra edge over your program when you make it public. As we study above, Different types of access modifiers in JAVA and their specification.

So keep in mind every time you use one of them as a class or interface access as they don’t only provide access but also overrides them. While there is always a concern regarding the accessibility of the method in the program. For instance, if an interface is assigned the ‘default’ access modifier in the superclass, it can override access modifiers used in the method’s subclass.

Note: Class includes variables, constructors, fields, and methods, and the interface includes specific fields or methods.

The above is the detailed content of Access Modifiers in Java. 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
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

Java Features for Modern Development: A Practical OverviewJava Features for Modern Development: A Practical OverviewMay 08, 2025 am 12:12 AM

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

Mastering Java: Understanding Its Core Features and CapabilitiesMastering Java: Understanding Its Core Features and CapabilitiesMay 07, 2025 pm 06:49 PM

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Can Java be run everywhere?Can Java be run everywhere?May 07, 2025 pm 06:41 PM

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

What is the difference between JDK and JVM?What is the difference between JDK and JVM?May 07, 2025 pm 05:21 PM

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Java features: a quick guideJava features: a quick guideMay 07, 2025 pm 05:17 PM

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.