Access Modifiers in Java

Access modifiers specifies the scope of a data member, method, constructor or class.There are four types of access modifiers in Java.

  • private : This access modifier is accessible only within class.
  • public : This access modifier is accessible everywhere. It has the widest scope among all other modifiers.
  • default: If we don’t provide any access modifier it will treated as default access modifier. The default modifier is accessible only within package.
  • protected:This access modifier is accessible within package and outside the package but through inheritance only.

Example of private access modifier

Methods of class should be public show that it can be accessible to outside the class.

    class Employee{  
    private int id;  
    public Employee(){
       id =100;
    }
    public void display(){
       System.out.println("Private Access Modifier");
      }  
    }  
      
    public class TestMain{  
     public static void main(String args[]){  
         Employee e=new Employee();  
         System.out.println(e.id);//Compile Time Error,as id is private data member  
         e.display();  
       }  
    }  

Example of public access modifier

Employee.java

    package mypack;
    public class Employee{  
    private int id;  
    public Employee(){
       id =100;
    }
    public void display(){
       System.out.println("Private Access Modifier");
      }  
    }  

TestMain.java

import mypack.*;
 public class TestMain{  
     public static void main(String args[]){  
         Employee e=new Employee();  
         e.display();  
       }  
    }  

Example of protected access modifier

Lets we have two class A and B. B class extends A class to inherit its data members and methods.

A.java

     package mypack;
      public class A{  
       private int x;  
       public A(){
         x=10;
      }
      public void display(){
        System.out.println("x="+x);
      }  
    }  

B.java

     package mypack;
      public class B extends A{  
      private int y;  
      public B(){
       y=20;
     }
    public void print(){
      System.out.println("x="+x);
      System.out.println("y="+y);
    } 

TestModifier.java

 package mypack;
  public class TestModifier{
    public static void main(String args[]){
      B b = new B();
      b.print();
    }
  }

Leave a Reply