×

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications.

Access modifiers in Java include:

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

Default Access Modifiers

Without providing an access modifier when defining a class, data member, or member function, the access modifier is set to default. Without using access modifiers, we can only access the class, data members, and member functions that we defined. The classes and methods are not usable outside of the current package.

Program for Default Access Modifiers in Java

Default_modifier1.java

package mypackage1;
class Default_modifier1 {  
    void display() {  
        System.out.println("Default_modifier1 class is invoked.");   
    }  
}  

Testing.java

\package m2;
import mypackage1.*;
public class Testing {  
    public static void main(String args[])   
    {   
        Default_modifier1 o1 = new Default_modifier1();   
        o1.display();   
    }   
}  

Output

Compile time error

Public Access Modifiers

We also use this access modifier in Java. The public keyword is used to invoke the public access modifier. It is one of the access modifiers with the most flexibility. We can access a class's methods and variables from anywhere in the programme that is designated as public. In other words, no restrictions on the extent of public data members are permitted.

Program1 for public Access Modifiers in Java

public_modifier.java

class public_modifier{   
    public void display()   
    {   
        System.out.println("Public Access Modifier");   
    }   
} 

Test1.java

public class Test1
{  
    public static void main(String args[])   
    {   
        public_modifier object1 = new public_modifier();   
        object1.display();  
    }   
}  

Output:

Difference Between Access Specifiers and Modifiers in Java

Program for public Access Modifiers in Java

Dog.java

public class Dog {
    public int no_of_legs;
    public void display() {
        System.out.println("I am an Dog.");
        System.out.println("I have " + no_of_legs + " legs.");
    }
}

Test2.java

public class Test2 {
    public static void main( String[] args ) {
        Dog d1 = new Dog();
        d1.no_of_legs = 4;
        d1.display();
    }
}

Output:

Difference Between Access Specifiers and Modifiers in Java

Protected Access Modifiers

Another access modifier that we employ in Java is the protected keyword, which we apply to the data members and member methods of a class. We can access a class's protected data members and member functions inside the same package, as well as subclasses in distinct packages.

Program for protected Access Modifiers in Java

Student.java

class Student   
{  
    protected String roll_number = "1423423";  
    protected String firstName = "M.";  
    protected String lastName = "Rohith";  
    protected String email = "R123@gmail.com";  
    protected int age = 21;
    protected int mobile_no = 9873994;
}  

Test4.java

class Test4 extends Student   
{  
    private int passOut = 2024;  
    public static void main(String[] args) {  
Test4 new_obj = new Test4();  
        System.out.println("Roll Number: " + new_obj.roll_number + "\nName: "+ new_obj.firstName + "" + new_obj.lastName);  
        System.out.println("Email: " + new_obj.email);  
        System.out.println("Age: " + new_obj.age);  
        System.out.println("Graduation Year: " + new_obj.passOut);
        System.out.println("Mobile number: "+ new_obj.mobile_no);
    }  
}  

Output:

Difference Between Access Specifiers and Modifiers in Java

Program for protected Access Modifiers in Java

Dog.java

class Dog {
    protected void display() {
        System.out.println("I am a Dog");
    }
}

BabyDog.java

class BabyDog extends Dog {
    public static void main(String[] args) {
BabyDog d1 = new BabyDog();
        d1.display();
    }
}

Output:

Difference Between Access Specifiers and Modifiers in Java

Private Access Modifiers

In Java, we apply the private access modifier by appending the private keyword to a class's data members and member methods. The class in which they are declared is the only one with access to private data members and member functions.

If we try to access them from a different package or from a different class within the same package, a compiler time error will be produced.

Program for private Access Modifiers in Java

Private_example.java

class Private_example   
{  
    private int passOut = 2024;  
}  

Test6.java

public class Test6 extends private_example  
{  
    protected String roll_number = "1423423";  
    protected String firstName = "M.";  
    protected String lastName = "Rohith";  
    protected String email = "R123@gmail.com";  
    protected int age = 21;
    protected int mobile_no = 9873994;
    public static void main(String[] args) {  
Test6 new_obj = new Test6();  
        System.out.println("Roll Number: " + new_obj.roll_number + "\nName: "+ new_obj.firstName + "" + new_obj.lastName);  
        System.out.println("Email: " + new_obj.email);  
        System.out.println("Age: " + new_obj.age);  
        System.out.println("Graduation Year: " + new_obj.passOut);
        System.out.println("Mobile number: "+ new_obj.mobile_no);
    }  
}  

Output

Compile time error

Here, passOut is declared as a private in private_example. Hence, it throws a compile time error while accessing it from another class.

Program for private Access Modifiers in Java

Student.java

class Student {
    private String s_name;
}

Test5.java

public class Test5 {
    public static void main(String[] main){
        Student N = new Student();
        N.s_name = "Rohith";
    }
}

Output:

Difference Between Access Specifiers and Modifiers in Java

We are attempting to access the Student class's private variable from the Test5 class, which causes an error to be generated.

Overcoming the private compile time error

We can utilize the getters and setters’ function to access those private variables without causing a compile-time error.

Program for private Access Modifiers in Java

Student.java

class Student {
    private String s_name;
    public String getName() {
        return this.s_name;
    }
    public void setName(String s_name) {
        this.s_name= s_name;
    }
}

Test8.java

public class Test8 {
    public static void main(String[] main){
        Student s1 = new Student();
        s1.setName("Rohith");
        System.out.println(s1.getName());
    }
}

Output:

Difference Between Access Specifiers and Modifiers in Java

What is the distinction between Access Specifiers and Access Modifiers?

In Java, there is no distinction between an access specifier and an access modifier. Both have the same meaning. Access specifier has been replaced with a new, official term called access modifier. For setting access levels for classes, variables, methods, and constructors, Java has four access modifiers.


Related Topics

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

What is String in Java?

What is String in Java? 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 Java...

4 minutes read.

How to Read XML Files in Java?

Introduction Today, we are going to learn about how to read XML files in java. Before, reading the XML Files let us learn about XML. XML Files The full form of XML is...

8 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Java String getChars() Method

Java String getChars() method copies characters from current String to the destination character array . Syntax: public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex) Parameters: srcBegin - index of the first character...

1 minute read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.