Java Online - Access Modifiers

Programming languages or concepts

Access Modifiers in java Programming language :-


 As the name suggest access modifiers in Java hills tourist ticket scope of class, constructor, data members and methods.

Access modifiers are keywords in Java that are used to set accessibility and access modifier restrict the access of a class constructor data members and methods in another class.


Java language has four access modifiers to control access level for classes and it's members.


  • Default
  • Public
  • Protected
  • Private


Java also support many non access modifiers such as static, abstract, synchronized, native, volatile, transient etc. 


Default access modifier

When no access modifier is specified for a class method for data member it is said to be having a default access modifier by default. 

 If you don't specify any access modifier then it is traded as a default modifier it is used to set accessibility within the package it means we cannot access its method or class for outside the package it is also known as package accessibility modifier

 Example:-

// Java program to illustrate default modifier 
package p1; 
  
// Class Geeks is having Default access modifier 
class Show
    void display() 
    
        System.out.println("Hello Student welcome!"); 
    


package p2; 

import p1.*; 
  
// This class is having default access modifier 
class msgdisplay
    public static void main(String args[]) 
    
        // Accessing class accessmodifier from package pack1 
        Show obj = new Show(); 
  
        obj.display(); 
    

Output:

Compile time error

in This example we will cricketer to package and classes in the packages will be having the default access modifier and we will try to access a class from one package from class of 2nd package.


Private:-

  •  The private access modifier is specified using the keyword private.
  • Private modifier is most distributed more modifier which allows access ability within within the same class only. We can set this modified to any variable method or even constructor as well.
  • The methods or data members declared as private are accessible only within the class in which they are declared.
  • Any other class of the same package will not be able to access these members.


Tags:
close