×

Access specifiers in Java

What are access specifiers in Java?

Access specifiers in Java are used to determine whether other classes can use a particular field or invoke a particular method. Access specifiers mainly specify the behavior of a class and the behavior of members such as instance variables and members. Here behavior means where we can access them like where we can access the class or where we can access the instance variables or where we can access the methods. So, this will be specified by the access specifiers.

Access specifiers in Java are of 4 types, they are

  • public
  • protected
  • private
  • default

Default is not a specifier. If we do not give any access specifier, then it will be default only.

By using the tabular representation one can easily understand access specifiers in Java.

Access SpecifiersWithin classWithin packageOutside package by subclass onlyOutside package
privateYesNoNoNo
protectedYesYesYesNo
publicYesYesYesYes
defaultyesYesNoNo

 These are the access levels of access specifiers in Java.

Access specifiers vs Access modifiers

Basically, access specifiers are nothing but access modifiers in Java. In olden languages like c++, we use terminology like specifiers to determine public, private, protected, and default so these four are considered specifiers. And except these four words remaining words like static, final, synchronized, etc… are by default considered as modifiers. This kind of terminology is perfectly valid for old languages like c++. But in Java, we don't have any kind of terminology like specifiers. We consider all these words as modifiers themselves. So, there is no big difference between access specifiers and modifiers in Java.

Now let us discuss about each access specifier briefly. First, let us see about class-level access specifiers and later about members' access specifiers in Java.

Private

Within the class only we can access this access specifier. So, once we give the keyword private to any method or variable means that a specific method or variable can only access within the class.

Let us understand this access specifier more briefly using an example.

PrivateExpl1.java

class X
{  
private int x = 50;  // using private access specifier for a variable
private void show() // using private access specifier for a method
{
System.out.println(" Welcome to JavaTpoint "); 
}  }  
 class PrivateExpl1{  
 public static void main(String args[])
{  
   X o = new X();  
   System.out.println(o.x); // we will get error 
   o.show(); // Error during the compile time  
   }  
}  

Output:

Access specifiers in Java

Code Explanation:

In the above code, we have first created a class X. Inside the class we have declared a variable and used the access specifier private. In the next step, we have created a method called show() which is also access specified by private. Next, we created a class called PrivateExp1. Inside the main method, we have created an instance or an object to class X. In the output statement, we have tried to print the variable of class X. But since the variable inside class X is specified by the access specifier private, we cannot access it. Hence, we will get compile time error. And in the next step, we also wanted to access the method show() which is also from class X and is also specified by the access specifier private. So, there also we got compile time error as output.

We can make a constructor private. But we cannot access it outside the class. To understand it more briefly let us consider the below program.

PrivateExpl2.java

class X
{  
private X() // creating a constructor and making it private
{
} 
void show()
{
System.out.println(" Welcome to JavaTpoint ");
}  
}  
class PrivateExpl2{  
 public static void main(String args[])
{  
   X o = new X(); // Error during compile time 
 }  
}  

Output:

Access specifiers in Java

Code Explanation:

In the above code, first, we have created a class called X. Inside class X we have created a constructor and made it private using the access specifier private. Next, we have created a method show(). Next, we created another class called PrivateExpl2. Inside the main method, we have created an instance or object to class X. Since the constructor is private, we cannot access it in another class. Therefore, we will get compile time error as output.

default

Default is not an access specifier in Java. If we do not give any access specifier, then it is considered as default. Within the package only we can access this specifier. That means we cannot access outside a package. This specifier in Java is more accessible than the private access specifier. But when compared to public and protected it is highly restricted.

To understand more about this access specifier in Java let us consider the below program.

X.java

package pack;  // creating the package
class X
{  
 Public static void main(String args[])
{
System.out.println(" Hello ! Welcome to JavaTpoint ");
}  
}  

Output:

Access specifiers in Java

Code Explanation:

In the above code, we have created a package called a pack. We have created a class called X. And inside the main method, we have just written the output statement. Since compiling and running a package is different when compared to a normal java file. We have compiled this package using the above format and have also run this package. We got the output as displayed in the above image which is Hello ! Welcome to JavaTpoint.

B.java

package mypack;  
import pack.*;  
class B
{  
  public static void main(String args[])
{  
   X o = new X(); // Error during the compile time   
   o.msg(); // Error during the compile time  
  }  
}  

Output:

Access specifiers in Java

Code Explanation:

In the above code, we have imported the package pack that we have created above. And we have created a class B and inside the main method, we have created an instance or an object to the class X which is under the package pack. Since the package pack is not public, we cannot access the methods and class of that package outside the package and hence we will get compile time error as output.

protected

This access specifier can be accessed within the package or outside the package. But it is accessed only through inheritance. But the condition here is this access specifier cannot be applied to a class or interfaces. We can apply this access specifier to methods or constructors or data members.

Dog.java

class Animal { // parent class
    protected void display() { // applying protected access specifier to the method
        System.out.println(" Hello ! My name is Animal ");
    }
}
// inheritance
class Dog extends Animal { // child class
    public static void main(String[] args) {
        Dog dog = new Dog(); // creating an instance or an object to the dog class
        dog.display(); // calling the method of the animal class
    }
}

Output:

Access specifiers in Java

Code Explanation:

In the above code, we have first created a class Animal and inside this class, we have created a method display(). And we have made it protected using the keyword protected. We have used inheritance to access the method of the class Animal. We have created a class called Dog which inherits all the properties of the parent class that is the class Animal. Inside the main method, we have created an instance or an object in the Dog class. Through the object of the Dog class, we have accessed the method display() of the parent class. Since we have used inheritance here, we can access the methods of the parent class even if they are protected. Hence, we got output without any compile time or run time error.

public

This is the most accessible access specifier among all the above. This will give access to class or method or variable anywhere in the program. This means we can access it inside class or outside the class or inside the package or outside the package.

Let us understand more about this access specifier in Java, let us consider the below example.

Y.java

package pack;  
public class Y {  
public void show() { System.out.println(" Hello ! welcome to JavaTpoint "); }  
}

Z.java

package mypack;  
import pack.*;  
class Z
{  
  public static void main(String args[]) {  
   Y o = new Y();  
   o.show();  
  }  
}  

Code explanation:

In the first code, we created a package called a pack. And we have also created a class called Y. We made the class public using the keyword public. Inside this class, we have created a method show() which is also public since we have written the keyword public in front of the method. In the next line, we have written the output statement.

In the next program, we have created a new package mypack and imported the package pack that we have created in the above program. We have created class Z and inside the main method, we have created an instance or an object to class Y which is imported from the package pack. In the next line, we have tried to display the show() method which is the method of class Y. Since class Y is public, we will get the output without any compile time or runtime errors.

Using Method Overriding with Access Specifiers in Java

MO.java

class E // parent class
{  
protected void show() // using access specifier protected
{
System.out.println(" Hello ! welcome to javaTpoint ");
}  
}  
public class MO extends E // child class
{  
void show() // method overriding
{
System.out.println(" Hello ! welcome to javaTpoint "); // error during the compile time
}  
 public static void main(String args[])
{  
   MO o = new MO();  // creating an instance or an object 
   o.show();  
   }  
}  

Output:

Access specifiers in Java

Code Explanation:

In the above code first, we have created a class E and inside the class, we have created a method show() and we have made it protected. Next, we have created another class which is MO that inherits all the properties of class E. There we have used method overriding. Since protected is used within the class only we will get the output as compile time error.

This is all about access specifiers in Java. Hope you have learned something new.


Related Topics

Java Integer compare() method

The compare() method of Integer class compares the two specified int values. Syntax public static int compare(int x, int y) Parameters The parameters ‘x’ and ‘y’ represent the first and second int values to...

2 minutes read.

Java Obfuscator

Obfuscation is the process of making something unclear or difficult to interpret. Obfuscators are being used in programming to protect the source code from hackers. In this article, we will...

8 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Java Final Keyword

In Java, the last keyword is used to limit the user. The applications of the java final keyword have large range of usage in program development. Last can be: variablemethodclass A final...

3 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

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

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

Equidigital in Java

In this section, we will understand what is an equidigital number and how to write Java programs to locate them. It is commonly asked in academic settings and Java coding...

4 minutes read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

How to create a mirror image of a 2D array in Java

Problem Statement We have provided a list of m x n. here m indicates rows, and n indicates columns). Printing the fresh matrices should result in a mirror reflection of an...

2 minutes read.