×

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 Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

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

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 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 Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.