×

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields.

If you are aware of C++ language, when we declare any member inside a class without public keyword then it is by default taken as private. But in Java, there are four different types of access modifiers, and if we do not specify access modifier for member or class it is considered as default modifier.

We can use modifiers with the class, but we can use only two access specifier (public or default) with the outer class. Whereas, for inner class we can use any of the four modifiers.

There are four types of access modifiers in Java:

  • Private: Its access level is only within the class. It can’t be accessed from outside that class.
  • Protected: Its access level is within the package and outside the package through child class.
  • Public: Its access level is everywhere because it can be accessed within the class, outside the class, within the package, and outside the package. This is why the main() method has always been defined by the public modifier.
  • Default: Its access level is only within the package because it cannot be accessed outside the package. If we do not specify and access modifier, it will be marked as default. It is more restrictive than protected.

Let's understand that where access modifier being used by a simple table:

Access Modifier Same Class Same package Subclass Same Package Non-subclass Different package Subclass Different Package Non-subclass
Private Yes No No No No
Default Yes Yes Yes No No
Protected Yes Yes Yes Yes No
Public Yes Yes Yes Yes Yes

Example to illustrate the working of access modifiers.

 classprivateDemo
 {
  int add; // default access
  publicint sub; // public access
  privateintdiv; // private access
  // declaring method to access c
  voidsetdiv(inti) 
  { 
  // setting div's value
  div = i;
  }
 intgetdiv() 
  { 
  // getting div's value
  returndiv;
  }
 }
 classaccessDemo
 {
  publicstaticvoid main(String args[]) 
  {
  privateDemoobj = newprivateDemo();
  obj.add = 10;
  obj.sub = 20;
  // obj.c = 100; // It will give a compile time Error! because of access violation
  // We must access div through its methods
  obj.setdiv(100); // it sets the value of div
 System.out.println("add, sub, and div: " + obj.add + " " +obj.sub + " " + obj.getdiv()); 
  }
 } 

Output:

add, sub, and div: 10 20 100

As we can see, inside the privateDemo class, add uses default access, which is the same as specifying public. sub is explicitly declared as public. And member div is declared private i.e. it cannot be accessed by code outside of the class. So inside the accessDemo class, div can’t be used directly. We accessed it through a public method i.e. setdiv() and getdiv().


Related Topics

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java Location

PATH is an environmental variable that the system software now uses to find executable files (.exe) or Java binaries ( java or javac command). Once chosen, a route cannot be...

3 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.

Composition in Java

Composition Java uses the composition method to implement a has-a connection. Composition allows us to reuse code in the same way that Java inheritance does. The "is-a" relationship is implemented using the...

3 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.