public private protected access modifier in java


private public protected in java class modifiers

Having the door would not ensure safety for home.  Locking the door is important and ensures the safety of the home. The same analogy applicable for Java object oriented feature as well. Writing a class in java would not provide abstraction and encapsulation. We have to write the code by exposing only the required information in the class by using proper access modifiers.

 

Access Modifiers:

Access modifiers are used to control the accessibility to classes, interfaces, fields, constructors and methods. In other words, we can use access modifiers to protect data and behaviors from the outside world. At a high level, access modifiers facilitate the encapsulation feature in Object-Oriented Programming. They are the core, fundamental and important concepts in Java which you have to grasp a deep understanding in order to write code properly, efficiently, securely.

Class method and variable members are usually given access control in exactly the same way, 3 access modifiers and 4 access levels (including default).

  • public                : Visible to the world
  • protected          : Visible to the package and all subclasses
  • default               : Visible to the package, the default. No modifiers are needed
  • private               : Visible to the class only

Default protection is what you get when you don’t type an access modifier in the member declaration. The default and protected access control types have almost identical behavior, but different in access methods in subclasses.  We are clear understanding of scope of each modifiers. Now how to decide access modifiers for our class methods. By default, all the class variables should be declared as “private” and exposed by accessor methods.

Ask the below three decision question for each method and constants. It would help us to decide the scope of the method.

 

Pass all the methods through these 3 decision and change the access modifier of the methods. It gives us strongest form of encapsulation.

Key Takeaways:

Access modifiers are,

in order to control the accessibility of the methods and members.

are  used for strong encapsulation.

are important, when you release code as a library for other programmers to use.

 

Tags: ,

You may also like