Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaProtected vs Private Access Modifiers in Java

Protected vs Private Access Modifiers in Java

Access modifiers are those elements in code that determine the scope for that variable. As we know there are three access modifiers available namely public, protected, and private. Let us see the differences between Protected and Private access modifiers. 

Access Modifier 1: Protected

The methods or variables declared as protected are accessible within the same package or different packages. By using protected keywords, we can declare the methods/variables protected.

Syntax:

protected void method_name(){

......code goes here..........

}

Example:

Java




// Java Program to illustrate Protected Access Modifier 
  
// Importing input output classes
import java.io.*;
  
// Main class 
public class Main {
  
  // Input custom string 
  protected String name = "Geeks for Geeks";
    
  // Main driver method 
  public static void main(String[] args) {
      
    // Creating an object of Main class 
    Main obj1 = new Main();
      
    // Displaying the object content as created
    // above of Main class itself  
    System.out.println( obj1.name );
     
}
}


Output

Geeks for Geeks

Access Modifier 2: Private 

The methods or variables that are declared as private are accessible only within the class in which they are declared. By using private keyword we can set methods/variables private.

Syntax: 

private void method_name(){

......code goes here..........

}

Example:

Java




// Java Program to illustrate Private Access Modifier
  
// Importing input output classes
import java.io.*;
  
// Main class
public class Main {
  
    // Input custom string
    private String name = "Geeks for Geeks";
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating an object of Main class
        Main obj1 = new Main();
  
        // Displaying the object content as created
        // above of Main class itself
        System.out.println(obj1.name);
    }
}


Output

Geeks for Geeks

Now after having an understanding of the internal working of both of them let us come to conclude targeted major differences between these access modifiers. 

Protected Private
The keyword used is ‘protected.’ The keyword used is ‘private.’
Protected can be used within the same class Private can be used within a same class
Protected can be used in the same package subclass Private can not be used in the same package subclass
Protected can be used in different package subclass Private can not be used in different package subclass
Protected can not be used in different package non-subclass Private can not be used in different package non-subclass
RELATED ARTICLES

Most Popular

Recent Comments