Access modifiers in Java

Until now, we have developed so many Java applications, created so many Java methods, variables and classes. But have you ever noticed the keywords like public, private etc, infront of these entities? Like in the main method of every program, we often write public static void main(), do you know what these keywords public or static mean? Well, these are Java modifiers and they have their specific functions to perform in the program.

In this tutorial we'll be discussing about what are Java modifiers and types of modifiers: Access modifiers and Non-access modifiers.


What are modifiers in Java?

In Java, modifiers are special keywords that help in changing/specifying the state or accessibility of a class, method, variable or field in Java. These modifiers determine the scope of a entity and present condition of the entities whether the entity is never-changing or never-accessible etc. 

In Java, there are 2 types of modifiers: Java Access modifiers and Java Non-access modifiers

In this tutorial, we'll be mainly focussing upon Access modifiers only.

Access modifiers in Java


Java Access modifiers specify the accessibility(visibility) or scope of the class, method, variable, constructor or field. They provide access control in Java. 

Suppose, you have a method named M1, In Java you have the privilege to restrict the accessibility of this method. Meaning you can set a limit on who can access this method, whether it would be accessible in this package only. Or in other packages also. Or only in this particular class or in only in its child classes etc. All these things can be specified using Java Access modifiers.

These access modifiers are also known as Java Access specifiers.

Access modifiers are of 4 types: 
  • private
  • protected
  • default
  • public
All these access modifiers can change the access level of any class, method, variable, constructor or field in Java.

* In Java, Along with classes we can only have public or protected access modifiers. Because private and protected access modifiers donot imply with Java classes. And in Java, we need to have a Class which can be accessible in the whole package, which is only possible through either public or default modifiers.

Also we can have only 1 public Java class in a program, which would contain the driving method or the main() method. And the source file is also name according to this public class.

> Public access modifier in Java

The Public access modifier is specified using public keyword. It can be accessible from anywhere(globally). Therefore, it has the widest scope of accessibility amongst all other modifiers.

But the only problem with using public access level is that, the class member declared as public would be accessible from anywhere by anyone. Thus, anyone can change or modify the data. 

Example : Both classes in different packages

package myPackage1;
class Test1{
public void printMessage(){ System.out.println("This is public access modifier");}
}

package myPackage2;
import myPackage1.*;
public class Test2{
    public static void main(String args[]){
        Test1 obj1 = new Test1();
        obj1.printMessage();
    }
}

OUTPUT

This is public access modifier

Here, both the classes are in different packages myPackage1 and myPackage2, but due to the use of public access modifier, the method of class Test1 of myPackage1 is accessible in the Test2 class of myPackage2 package. Thus proving that public access modifier can be accessed from anywhere.

> Default Access modifier in Java

The default access modifier is specified automatically when no other modifier is specified. We need not use any special keyword to use this modifier, it is the default access modifier in Java. The default modifier is accessible only in the current package, it cannot be accessed from outside the package in any way.
It is more restricted than the public access modifier.

Example 1 : Both classes in different packages

package myPackage1;
class Test1{
void printMessage(){ System.out.println("This is public access modifier");}
}

package myPackage2;
import myPackage1.*;
public class Test2{
    public static void main(String args[]){
        Test1 obj1 = new Test1();
        obj1.printMessage();
    }
}

OUTPUT

This would give a compile time error as the printMessage() method is with default access level, so it is only accessible inside its current package, i.e myPackage1, that means only the classes and interfaces inside myPackage1 can access printMessage() method. Outside myPackage1, it cannot be accessed.

Example 2 : Both classes in the same package

package myPackage1;
public class Test2{
    public static void main(String args[]){
        Test1 obj1 = new Test1();
        obj1.printMessage();
    }
}
class Test1{
    void printMessage(){ System.out.println("This is default access modifier");}
    }

OUTPUT

This is default access modifier

Here, both the classes Test1 and Test2 are inside the same package myPackage1. So the method printMessage() with default access level is accessible by Test2 class in this case.

> Protected Access modifier in Java

The protected Java access modifier is specified using the protected keyword. Any entity marked with protected access level would be accessible in the current package(by all its classes and interfaces) and in other packages also, but only through inheritance(by child classes).

It is less restrictive than the default modifier and more restrictive than public access modifier.

Example : Both classes in different packages, but 1 class child of other class

package myPackage1;
class Test1{
 protected void printMessage(){ System.out.println("This is protected access modifier");}
}

package myPackage2;
import myPackage1.*;
public class Test2 extends Test1{
    public static void main(String args[]){
        Test1 obj1 = new Test1();
        obj1.printMessage();
    }
}

OUTPUT

This is protected access modifier

Here, the class Test2 of package myPackage2 is a sub-class or a child-class of class Test1 of myPackage1, thatswhy it is able to access the protected method. It also also access it, if it was present in the myPackage1 package. But if Test2 class had not been a child of Test1 class, being in different packages, then Test2 would have not been able to access printMessage() method.

Example 2 : Both classes in the same package

package myPackage1;
class Test1{
 protected void printMessage(){ System.out.println("This is protected access modifier");}
}
public class Test2{
    public static void main(String args[]){
        Test1 obj1 = new Test1();
        obj1.printMessage();
    }
}

OUTPUT

This is protected access modifier

Here, Since both the classes are in the same package, thats why the protected method is again accessible by Test2 class.

Example 3 : Both classes in different packages with no child-parent relationship

package myPackage1;
class Test1{
 protected void printMessage(){ System.out.println("This is protected access modifier");}
}

package myPackage2;
import myPackage1.*;
public class Test2{
    public static void main(String args[]){
        Test1 obj1 = new Test1();
        obj1.printMessage();
    }
}

OUTPUT

Compile time error.

> Private Access modifier in Java

The private access modifier in Java is specified using the private keyword. Any Java entity marked with private access level can only be accessible in the current class only. Only the member of that particular class would access that private member. It cannot be accesses outside the class by any method. 

The private modifier also helps in achieving abstraction and encapsulation by Data hiding, meaning the members that are private would not be visible to outer world(outside the specific class), meaning no one can change/access the values of these members. In such scenarios, getter & setter methods are used to access of modify the values. 

It is the most restrictive amongst other access modifiers.

Example : Both the classes in same package, and using getter/setter methods.

package myPackage1;
class MyClass1{
    private int age;
    private String name;
    
    void setName(String name){
    this.name=name;
    }
    
    void setAge(int age){
    this.age=age;
    }
    
    String getName(){
    return this.name;
    }
    
    int getAge(){
    return this.age;
    }
    }

    public class mainClass{
    MyClass1 ob1 = new MyClass1();
    ob1.setName("ABC");
    ob1.setAge(10);
    System.out.println(ob1.getName() + " " + ob1.getAge());
    }

OUTPUT

ABC 10

Here, the instance variables age and name are private, so they can only be accessed inside their class MyClass1, so to access and modify them, we need getter and setter methods. As shown in the example.

Example 2 : accessing private members without getters and setters

package myPackage1;
class MyClass1{
    private int age;
    private String name;
    }

public class mainClass{
    MyClass1 ob1 = new MyClass1();
    ob1.age = 10;  //Compile time error
    ob1.name = "ABC";  //Compile time error
    }

OUTPUT

Compile time error, as private members cannot be accessed outside the class in which they are declared. 

Summary Table: 


FAQs

Ques 1. What are packages in Java?
Ans. A Java package is a mechanism to encapsulate a group of classes, sub-packages or interfaces. They are just like a folder or a directory for saving the source code files of the Java programs. 

Ques 2. What are getters and setters in java?
Ans. These are 2 conventional methods used to set the values of instance variables and retrieving them for an object. They provide protection to the data, i.e, abstraction. The getter method returns the value, whereas setter sets of updates the value.

Ques 3. What is Abstraction in Java?
Ans. Abstraction, in general, is the process of hiding some details and showing only essential information to the user. In Java, abstraction can be achieved by using abstract classes or interfaces.

Ques 4. What is Inheritance in Java?
Ans. Inheritance is the process of defining a new Java class based upon an existing Java class by extending its common data members and methods. It makes the code reusable and efficient.

Ques 5. What is use of extend keyword in Java?
Ans. It indicates that a Java class is inherited from another Java class. It is used to achieve Inheritance in Java.

Ques 6. What is Encapsulation in Java?
Ans. It is the process of wrapping up code and data together in a single unit. 

Ques 7. What is Data hiding in Java?
Ans. In Java, during encapsulation, the class members are usually set to private, and they become hidden from the outer world, this is known as Data Hiding in Java. 

Ques 8. What is the use of import keyword in Java?
Ans. Import keyword is used to import Packages into classes.

Ritish

Just a novice blogger

Post a Comment (0)
Previous Post Next Post