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
import java.io.*;
public class Main {
protected String name = "Geeks for Geeks" ;
public static void main(String[] args) {
Main obj1 = new Main();
System.out.println( obj1.name );
}
}
|
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
import java.io.*;
public class Main {
private String name = "Geeks for Geeks" ;
public static void main(String[] args)
{
Main obj1 = new Main();
System.out.println(obj1.name);
}
}
|
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 |
Last Updated :
28 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...