Access Modifiers in Java

This article will explain one of the OOP concepts, Access Modifiers, in Java along with some basic examples to get a clear understanding of the concept.

Access Modifiers

Access modifiers are keywords that specify the access allowed to the classes, methods, constructor, data members and so on; in other words a class can control what information or data can be accessible by other classes.

In Java there is the provision of numerous of access modifiers for setting the levels you want from classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no access modifier is specified. You should possibly minimize access levels whenever dealing with encapsulation in Java.

Basically there are the following two types of modifiers in Java:

  • Access modifiers
  • Non-access modifiers

modifiers in Java

Non-access modifiers
are synchronized, native, static, abstract, volatile, transient and so on but here we will discuss only access modifiers.

The following are the four access modifier levels:

  • Visible to the package, the default (no modifiers are needed)
  • Visible to the class only (private)
  • Visible to the world (public)
  • Visible to the package and all sub-classes (protected)

The following are the four types of access modifiers:

  • Default
  • Private
  • Public
  • Protected

 

access modifiers 
Default access modifiers

In Java, when no access modifier is used then it is called a default specifier. Any class, field, method or constructor that has not declared an access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.

In other words, if you don't use any modifier, it is treated as default by default. The default modifier is accessible only within the package.

Example

Here we are making two different packages, one is article and the other is defaultpackage. In each package we have made one class, Main.java and Greet.java and when trying to access the Greet class from outside its package and since the Greet class is not public it cannot be accessed from outside its package.

Greet.java
  1. package article;  
  2.   
  3. public class Greet {  
  4.   
  5.    void msg(){  
  6.        System.out.println("Hello..!! How are you..??");  
  7.    }  

Main.java
  1. package defaultpackage;  
  2. import article.*;  
  3.   
  4. public class Main {  
  5.   
  6.     public static void main(String[] args) {  
  7.          
  8.         Main m=new Main();  
  9.         m.msg();  // compile time error  
  10.     }  

In the preceding example, the scope of the class Greet and method msg() is default so it cannot be accessed from outside the package.

The preceding example can provide the output properly if both of the classes are located in the same package.

Private access modifiers

The fields or methods that are declared as private that are the most restrictive cannot be used for classes and Interfaces. Fields, methods or constructors declared as private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.

In other words, if a method or variable is marked as private, then only code inside the same class can access the variable, or call the method. Code inside subclasses cannot access the variable or method, nor can code from any external class.

If a class is marked as private then no external class can access the class. This doesn't really make much sense for classes though. Therefore, the private access modifier is mostly used for fields, constructors and methods.

Example

In this example we have created two classes, House and Details. Class House contains a private method and private data members and we are trying to access these private members and methods from outside the class that cannot be accessed. We get a compile time error.

  1. class House  
  2. {  
  3.     private int HNo=211;  
  4.     private String Town="Nagra";  
  5.     private String city="Jhansi";  
  6.     private void show()
        {  
  7.         System.out.println("Welcome to my house");  
  8.     }  
  9. }  
  10. public class Details  
  11. {  
  12.     public static void main(String args[])
        {  
  13.         House h=new House();  
  14.         System.out.println(h.HNo);  //compile time error  
  15.         System.out.println(h.Town);  //compile time error  
  16.         System.out.println(h.city);   //compile time error  
  17.         h.show();   //compile time error  
  18.     }  

If you make any class constructor private then you cannot create an instance of that class from outside the class.

A class cannot be private or protected except a nested class.

Public access modifiers

The Public keyword is also the easiest of the Java access modifiers because of its nature. A variable or method that is declared as public means that any class can access it. This is useful for those variables that should be accessible by your entire application. Usually common routines and variables that need to be shared everywhere are declared public.

In other words, fields, methods and constructors declared public that are least restrictive within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.

A class, method, constructor, interface and so on declared as public can be accessed from any other class. Therefore fields, methods and blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

However if the public class we are trying to access is in a different package then the public class still must be imported.

Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example

House.java

  1. package Newpack;  
  2.   
  3. public class House  
  4. {  
  5.     public int HNo=211;  
  6.     public String Town="Nagra";  
  7.     public String city="Jhansi";  
  8.     public void show()
        {  
  9.         System.out.println("Welcome to my house");  
  10.     }  
  11.     public void print()
        {  
  12.         System.out.println("You need coffee..??");  
  13.     }  

Details.java
  1. package Public;  
  2. import Newpack.*;  
  3.   
  4. class Details  
  5. {  
  6.     public static void main(String args[])
        {  
  7.         House h=new House();  
  8.         System.out.println(h.HNo);  
  9.         System.out.println(h.Town);   
  10.         System.out.println(h.city);     
  11.         h.show();  
  12.         h.print();  
  13.     }  

Output
 
Output 

Protected access modifiers

The Protected keyword is like one of the most typical Java access modifiers, but it is not difficult to understand yet because Protected variables and methods allow the class itself to access them, along with classes inside the same package are allowed to access them and also subclasses of that class are allowed to access them.

Those variables, methods and constructors that are declared protected in a superclass can be accessed only by the subclasses in other packages or any class within the package of the protected member's class.

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. The protected access modifier can be applied on the data member, method and constructor. It cannot be applied to the class.

The protected access modifier is accessible within a package and outside the package but through inheritance only.

Example

In this example we have created two packages, public and newpack. Class House of newpack is public so it can be accessed from outside the package. But the show() and print() methods are declared as protected, hence it can be accessed from outside the class only through inheritance.

House.java

  1. package Newpack;  
  2.   
  3. public class House  
  4. {  
  5.     public int HNo=211;  
  6.     public String Town="Nagra";  
  7.     public String city="Jhansi";  
  8.     protected void show()
        {  
  9.         System.out.println("Welcome to my house");  
  10.     }  
  11.     protected void print()
        {  
  12.         System.out.println("You need water..??");  
  13.     }  
  14.     protected void display()
        {  
  15.        System.out.println("Have some rest.");  
  16.     }  

Details.java
  1. package Public;  
  2. import Newpack.*;  
  3.   
  4. class Details extends House  
  5. {  
  6.     public static void main(String args[])
        {  
  7.         Details d=new Details();  
  8.         System.out.println(d.HNo);  
  9.         System.out.println(d.Town);  
  10.         System.out.println(d.city);  
  11.         d.show();  
  12.         d.print();  
  13.         d.display();  
  14.     }  

Output

Details

Up Next
    Ebook Download
    View all
    Learn
    View all