Access Modifiers in Java

Access Modifiers in Java

In this article, I am going to discuss Access Modifiers in Java with Examples. Please read our previous where we discussed Encapsulation in Java. At the end of this article, you will understand what is Access Modifiers in Java and its types with examples.

What are Access Modifiers in Java?

You must have seen public, private, and protected keywords while practicing java programs, these are called access modifiers. The access modifiers in Java specifies the accessibility or scope of classes, interfaces, variables, methods, constructors, data members, and setter methods. Access modifiers can be specified separately for a class, its constructors, fields, and methods. An access modifier restricts the access of a class, constructor, data member, and method in another class.

Java provides access control through three keywords – privateprotected, and public. We are not required to use these access modifiers always, so we have another one namely “default access“, “package-private” or “no modifier“.

There are two levels of access control:
  • At the top-level— public, or package-private (no explicit modifier).
  • At the member level— public, private, protected, or package-private (no explicit modifier).

Access Modifiers in Java

Types of Access Modifiers in Java

There are four types of access modifiers available in java:

  1. Default – No keyword required
  2. Private
  3. Protected
  4. Public
Default Access Modifier:

When we do not mention any access modifier, it is called the default access modifier. Declarations are visible only within the package (package private). The default access modifier means that code inside the class itself, as well as code inside classes in the same package as this class, can access the class, field, constructor, or method which the default access modifier is assigned to. Therefore, the default access modifier is also sometimes referred to as the package access modifier. This access is more restricted than public and protected but less restricted than private.

Example of Default Access Modifier in Java:

In this example, we have created two packages A and B. We are accessing the Demo1 class from outside its package, since Demo1 class is not public, so it cannot be accessed from outside the package.

package A;
public class Demo1 {
 void msg(){
  System.out.println("Hello World");
  } 
}

package B;
import B.*;
public class Demo2 {
  public static void main(String args[]){ 
  //accessing class Demo1 from package A 
     Demo1 obj = new Demo1();//Compile Time Error  
     obj.msg();//Compile Time Error  
    } 
}

Output: Compile Time Error

Private Access Modifier:

The private access modifier is specified using the keyword private. The scope of private modifier is limited to the class only.

  1. Private Data members and methods are only accessible within the class
  2. Class and Interface cannot be declared as private
  3. If a class has a private constructor then you cannot create the object of that class from outside of the class. A private constructor can still get called from other constructors, or from static methods in the same class.
Example of Private Access Modifier in java:
package Demo;

public class PrivateAccessModifier {
 private double num = 100;
    private int square(int a){
  return a*a;
    }
}
public class Example{
 
    public static void main(String args[]){  
    PrivateAccessModifier obj = new PrivateAccessModifier();  
  System.out.println(obj.num); //compile time error
  System.out.println(obj.square(10)); //compile time error
    } 
}

Output: Compile Time Error

In this example, we have created two classes PrivateAccessModifier and Example. PrivateAccessModifier class contains private data members and private methods. We are accessing these private members from outside the class, so there is a compile-time error.

Protected Access Modifier :

The protected access modifier is accessible within the package and outside the package but through inheritance only. The protected access modifier is specified using the keyword protected. Protected data members and methods are only accessible by the classes of the same package and the subclasses present in any package. The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however, methods and fields in an interface cannot be declared protected.

Example of Protected Access Modifier in Java:

In this example, we have created two packages A and B. The class Test which is present in package A is able to call the addTwoNumbers() method, which is declared protected. This is because the Test class extends class Addition and the protected modifier allows the access of protected members in subclasses (in any packages).

package A;

public class Addition {
 protected int addTwoNumbers(int a, int b){
  return a+b;
    }
}

package B;
import A.*;
public class Test extends Addition{
    public static void main(String args[]){
   Test obj = new Test();
   System.out.println(obj.addTwoNumbers(11, 22));
     }
}

Output: 33

Public Access Modifier :

The public access modifier is specified using the keyword public. The public access modifier is accessible everywhere. It has the widest scope among all other modifiers. The member variable or method is accessed globally. This modifier doesn’t put any restrictions on access. The Java access modifier public means that all code can access the class, field, constructor, or method, regardless of where the accessing code is located. If the public class we are trying to access is in a different package, then the public class still needs to be imported.

Example of Public Access Modifier in Java:
package Demo;

//public class
public class Animal1 {
 // public variable
 public int legCount;

 // public method
 public void display() {
     System.out.println("I am an animal.");
     System.out.println("I have " + legCount + " legs.");
 }
}

public class PublicAccessModifier {
 public static void main( String[] args ) {
     // accessing the public class
     Animal1 animal = new Animal1();

     // accessing the public variable
     animal.legCount = 4;
     // accessing the public method
     animal.display();
 }
}

Output:

Example of Public Access Modifier in Java

Note:

  • Private and Protected access modifiers cannot be used for class and interfaces.
  • If no keyword is mentioned then that is the default access modifier.
  • The access level of a public modifier is everywhere.
  • If other programmers use your class, try to use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.
  • Avoid public fields except for constants.
Access Modifiers visibility in Java:

Access Modifiers visibility in Java

In the next article, I am going to discuss Inheritance in Java with Examples. Here, in this article, I try to explain Access Modifiers in Java with examples. I hope you enjoy this Access Modifiers in Java with examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *