What is the difference between Public, Private, Protected and Default in Java?
You must have noticed the keyword Public, Private, Protected and Default being used in a Java Program. These keywords are called Access Modifiers. An access modifier restricts the usage of a class, constructor or method in another class. In Java we have four types of access modifiers, namely:
- Default
- Private
- Protected
- Public
Before digging up about these access modifiers, make sure you know about Packages in Java.
Default Access Modifier
When we don`t specify any access modifier, it is then said to be default access
modifier.
The scope of this access modifier is limited to the package only. What it indicates is, say
we have a class A with default access modifier, then only the classes of
that particular
package which contains class A can access this class. No other class outside this
package
will be able to access the class A.
Let us take an example in order to understand this better.
Here we have declared the function addTwoNumbers as default since no access modifier is specified. Let us try to import this package in another class and use this function.
Output
Let us see the output of the above code.
The error clearly specifies the restriction of default access modifier.
Private access modifier
The scope of private access modifier is limited to the class only. Anywhere outside the class, it is inaccessible. Let us see an example for private access modifier.
Output
Let us look at the output of the above example code.
The errors displayed clearly mentions the restrictions of private access modifier outside the class in which it is declared.
Protected access modifier
Protected data members and methods are accessible by the classes of the same package and
subclasses present in any package.
Let us take an example to understand this better.
Let us try to call this addTwoNumbers method in another package and see what happens.
Output
Let us look at the output of the above example code.
Voila! We got an output without any errors. You can compare protected access modifier with default access modifier and the only difference you will find between them is, the visibility in sub classes provided by the protected access modifier.
Public access modifier
There are no restrictions in the usage of public access modifier, the methods,
members and
classes declared as public are accessible from anywhere.
Let us take an example to visualize public access modifier.
Now, let us import this package in another class and try to use the function addTwoNumbers.
Output
Let us look at the output of the above example code.
You can compare this example with the previous protected access modifier`s example and find that we can directly use the class Addition inside the class Test by just declaring the function addTwoNumbers as public.
Summary
To summarise all the access modifiers and their scope, let us look at the below table which will give you a brief about what this article conveys.