×

Access modifiers in Java

Access modifiers in Java with Example

In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier.

If we talk about access modifier, there are four types of access modifier.

  1. default
  2. private
  3. public
  4. protected

Access modifier restricts the access of data members, methods, class, and constructors.

Access modifiers in Java with Example

Access modifiers also specify the access level of classes, variable methods, and constructor.

default access modifier

When no modifier is specified for a class, method, or data member then Java compiler consider it as default modifier.

The class, data members or methods having default access modifier are accessible only within the same package.

Example

A.java
package core2;
class A{ 
  void disp(){System.out.println("Hiii…");} 
} 
B.java
package core1; 
import core2.*; 
class B{ 
  public static void main(String args[]){ 
   A obj = new A();//Compilation  Error 
   obj.disp();//compilation Error 
  } 
}

Output

Compile time error

In the given example, access modifier (Scope) of A and the given method disp() are default then both are accessible within the same package. We are using two different package core1 and core2 so this program will throw a compilation error.

Java Private access modifier

It is a class level modifier; in other words, the scope of private modifier is limited to the class only. Some essential points about private access modifier are:

  • Methods and private data members are only accessible within the class.
  • In Java, a class and interface cannot be declared as private.
  • If we declare a constructor as private, then we cannot create the object of that class from outside of the class.

Example

class A{ 
private int n=40; 
private void disp(){System.out.println("This is a private method");} 
} 
public class Demo{ 
 public static void main(String args[]){ 
   A obj=new A(); 
   System.out.println(obj.n);//Compile Time Error 
   obj.disp();//Compile Time Error 
   } 
}

Output

Compile time error

In the given example, we are trying to access private data member n and private method disp() from outside the class. So it will lead to compilation error.

Java Private constructor

Example

class A{ 
private A(){}//private constructor 
void disp(){System.out.println("in constructor A");} 
} 
public class Demo{ 
 public static void main(String args[]){ 
   A obj=new A();//Compile Time Error 
 } 
}

Output

Compile time error

In the given an example, we have declared a constructor A() as private, so we cannot create the instance of class A. it will lead to a compilation error.

Java public access modifier

The public access modifier has the widest scope among all other modifiers. It can be accessed from everywhere. It is specified using the keyword "public."

Example

A1.java
package core2;
public class A1{ 
public void disp(){System.out.println("This is public modifier");} 
} 
B.java
package core1;
import core2.*;
class B{ 
       public static void main(String args[]){ 
        A1 obj = new A1(); 
        obj.disp(); 
       } 
     }

Output

This is public modifier
  • Try to use most restrictive access level that makes sense for a particular member therefore always Use private modifier unless you have a good reason not to.
  • Try to avoid public fields except for constants.

Java Protected access modifier

The "protected" keyword is used to specify the protected access modifier. It is accessible within the same package or outside the package through inheritance.

A1.java
package core2;
public class A1{ 
protected void disp(){System.out.println("in protected method disp");} 
} 
B1.java
package core1;
import core2.*;
class B1 extends A1{ 
  public static void main(String args[]){ 
   B1 obj = new B1(); 
   obj.disp(); 
  } 
}

Output

in protected method disp

Related Topics

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 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.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Java CountDownLatch

Another crucial classes for concurrent execution is CountDownLatch. It is a synchronisation tool that enables one or more threads to await until a series of tasks started by another thread...

4 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.