×

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

Constructor in Java with Example

Java Constructor  The constructor is used for object initialization. It's a block of code that initializes a newly created object. It contains a collection of statements that are executed at the...

5 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Deadlock Prevention and avoidance in Java

This tutorial will discuss deadlock prevention and Avoidance in Java programming language. Introduction Multithreading in Java includes deadlock. We can multitask by running several threads concurrently in the multithreading environment. Deadlock occurs...

4 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.