Access Modifiers in Java will help you to structure your program for suitable scoping. This article will assist you in learning the difference between private, public and protected access modifiers. Some examples are also explained about how to use these access modifiers.
Public access modifier is the most popular keyword used in Java. Public access modifier is the most easiest modifier to use because it can be accessed by the whole function. Typically common variables and routines which are in need to shared everywhere is declared as public. classes used in public modifier are least protected which means the methods and variables used under public class can be accessed from anywhere.
The variables and methods are most protected in private modifier. Private modifier allows only the permitted functions which can access those class. Private variable or method can be accessed by only one way; which is the private variables are accessed only from within the class. Private classes are only be accessed from Java class which owns it. When there is no need to use the method or variable outside the class private modifiers are used.
Protected is the most trickiest access modifier in Java. the variables and methods declared under private modifiers, allow only the class inside them to access it.
Let us consider the following program as an example:
public class X
protected int in;
// Please Note it down that the class Y belongs to the same package as class X
public class Y
public void AnyMethod()
// create an entity of class X
X anyInstance = new X();
public class Z extends X
public void anyOtherMethod()
in = 89;
In the above program both the classes belong to the same package called “Random Package”.
- Many: Java interview Q&A available here
The declaration fl in class X, it can be noticed that it has no access modifiers. When an access modifier is not declared the compiler will conclude the variable as package access. The variable declared in package access will allow permission to all the other variables declared in the same package. This means the variable will allow access only to all classes declared in the same package. In the above program class Y variables can access Class X because both are present in same class. Class X can access f1 variables in class Y and Class Y can also access variable “in”, which was originally declared in Class X. In Java, Methods declared as declared as protected can be accessed by class with same name in its own definition. Any class derived from any package.
Class that are derived have access to protected variables or methods.
The variable “in” can be accessed by the class Z in the example given above. “I1” variable are actually derived from class A. The access of the variable “in” is highly authentic because it was declared in protected class ‘X’. So any variable declared in protected modifier will allow access to variables from derived class.