Access modifiers in Java
"Which access modifiers are you familiar with and what is the difference between them?"
This is a very common interview question, that can at times catch a candidate off guard. In this post, we will discuss the different access modifiers available in Java, and the differences between them.
In Java, there are 4 main access modifiers that are basically reserved keyword which allow us to control access to fields, methods and classes from other entities. Confused? Let's see if we can clear things up a bit.
Public
Private
Protected
Protected means that the member will be accessible within that paticular class, within the same package and through a child class, but, will not be available globally.
Default
Default basically means that we do not explicitly declare an access modifier. That member/method/class will be reachable/available within the boundries of the class and package. It cannot be accessed form outside the class, through a sub class or globally (outside of the package).
For example:
In the following screenshot you can see the project I have created for this demonstration.
In this project, I have 2 packages: a, b.
In package a - I have the "Animal" class, and the "Demo" class.
In package b - I have I have the "GlobalDemo" class.
As you can see, the Animal class contains a public String breed.
Since breed is public, I can access it once I instantiate the Animal class, Demo class, or GlobalDemo class, and it will work just fine.
Now, If I decide to change the access modifier of breed to private, watch what would happen:
As you can see, it tells me that breed is private in class Aminal in package a, therefore I cannot access it from outside of the Animal class.
Now, let's change the modifier of breed again, but this time to protected and try to access it from the Demo class inside the same package (a).
There are no Errors. Now, let's see what is going on in the GlobalDemo class which is in another package (b)
As expected, "protected" members cannot be accessed from outside the class. Actually, the IDE will not even display it in the intellisense for the class instance.
The same thing would happen for a member with default access.
As you can see in the example below, the String breed is available in the Demo class but not for the GlobalDemo class.
Great job for publishing such a nice article. Your article isn’t only useful but it is additionally really informative. Thank you because you have been willing to share information with us.PTE Gold Coast
ReplyDeletePretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. I hope you post again soon. Big thanks for the useful info. tithing online
ReplyDeleteThis comment has been removed by the author.
ReplyDelete