Saturday, June 8, 2013

Access modifiers in Java

Hi All,
Welcome to Java-recent.
In this post we will discuss different access modifiers  ,their implementation and usage in Java programming language.

Access modifiers:- As the name indicates the main purpose of them is to control the access of different elements in Java like
Classes,methods,attributes etc.

Note:-Here onwards in this article we will represent Access Modifiers as AM
We need to restrict them because unwanted code or classes need not access them.

There are two levels of Access modifiers:-
  1. High/top/Class level :- We have two of them in this category. Public and default(package-private,no explicit modifier)
    A Class will have only Public or default AM
  2. Member/variable level :- we have Public,Protected,default,private.

In total there are four AM's

  1. Public:- Accessible to all elements
  2. Protected:-Accessible to elements in same package and sub classes(Child)
  3. Default/package-private:- Accessible to elements in same package
  4. Private:- Accessible to only that particular class


Access Modifier
Class
Package
Subclass/child class
World/Every element
Public
Y
Y
Y
Y
Protected
Y
Y
Y
N
default
Y
Y
N
N
private
Y
N
N
N



Descending order of AM scope:-

       Public>Protected>default>private

Conclusion:-
  • Private is the most restrictive AM,only that class elements will be able to access
  • Members or instance variable of public can be accessed by all classes
  • Always implement most restricted AM's as per the requirement
  • Always declare instance variables as private,if you want them to access it use setter and getter method


                      Happy learning


No comments:

Post a Comment

Like and Share