Access Modifier in Java

Access Modifier

What is Access Modifier?

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.

                                                                   

There are four types of Java access modifiers:

     1.    Private

     2.    Default

     3.    Protected

     4.    Public

1.Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.

Note: The scope of private modifier is limited to the class only

->Private Data members and methods are only accessible within the class                                                          
->Class and Interface cannot be declared as private
->If a class has private constructor then you cannot create the object  of that class from outside of the class.

2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.

When we do not mention any access modifier, it is called default  access modifier. The scope of this modifier is limited to the package only. This means that if we have a class with the default access modifier in a package, only those classes that are in this    package can access this class. No other class outside this package can access this class. Similarly, if we have a default method or data member in class, it would not be visible in the class of another package.

3.Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.

4.Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.     

The public access modifier has the widest scope among all other access modifiers.

Classes, methods or data members which are declared as public are accessible from every where in the program. There is no restriction on the scope of a public data members.

 

     Lets see the scope of these access modifiers 


Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors.The four access levels are:

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





Comments

Popular posts from this blog

Java Stack and Heap: Java Memory Allocation Lesson.

What is JVM, JDK and JRE in Java?

How To Set Getters And Setters Method In java Using Eclipse?