Code Pumpkin

Access Modifiers in Java

September 2, 2017
Posted by Dipen Adroja

In this article, we will discuss one of the basic feature of Java- Access Modifiers. As the name suggests access modifiers in Java helps to restrict the scope of a class, constructor, variable, method or data member. Assigning an access modifier to a class, constructor, field or method is also sometimes referred to as "marking" that class, constructor, field or method as that which the access modifier specifies. Java gives compile time errors for the wrong usage of the access modifier.

There are four types of access modifiers available in java:

  1. Default(package) – No keyword required
  2. Private
  3. Protected
  4. Public

1. Default(package): 

The default access modifier also referred as package access modifier. When no access modifier is specified for a class, method or data member – It is said to be having the default access modifier by default. The class, data members or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package.

Let's take an example to understand it better.


package com.codepumpkin.demo;
 
//Class Hello is having Default access modifier
class Hello
{
    void display()
       {
           System.out.println("Hello World!");
       }
}


//Java program to illustrate error while 
//using class from different package with
//default modifier
package com.codepumpkin.demo1;
import com.codepumpkin.demo.*;
 
//This class is having default access modifier
class Demo
{
    public static void main(String args[])
       {  
          //accessing class Hello from package com.codepumpkin.demo
          Hello hello = new Hello();
 
          hello.display();
       }
}

Output:

Compile time error

2. Private:

The private access modifier is specified using the keyword private. If a method or variable is marked as private (has the private access modifier assigned to it), then only code inside the same class can access the variable, or call the method. The code inside subclasses cannot access the variable or method, nor can code from any external class.
Classes or interface can not be declared as private as marking it private will make the class useless.
It is normal practice to define the class members variables as private and provide a proper getter-setter method to get and set the values for the fields.

Check the example below:
 


package com.codepumpkin.demo;

class A
{
   private void display()
    {
        System.out.println("Hello World!!!");
    }
}
 
package com.codepumpkin.demo;

class B
{
   public static void main(String args[])
      {
          A obj = new A();
          //trying to access private member of class A
          obj.display();
      }
}

Output:

Compile time error

error: display() has private access in A
        obj.display();

3. protected:

The protected access modifier provides the same access as the default access modifier, with the addition that subclasses can access protected methods and member variables (fields) of the superclass. This is true even if the subclass is not located in the same package as the superclass.

Let's see one example for this as well.


package com.codepumpkin.demo;

class A
{
   protected void display()
    {
        System.out.println("Hello, World!!!");
    }
}

 
package com.codepumpkin.demo1;
import com.codepumpkin.demo.*;

class B extends A
{
   public static void main(String args[])
   {  
       B obj = new B();  
       obj.display();  
   }  
}

Output:

Hello, World!!!

4. public:

The Java access modifier public means that all code can access the class, field, constructor or method, regardless of where the accessing code is located. The accessing code can be in a different class and different package.


package com.codepumpkin.demo;

class A
{
   public void display()
    {
        System.out.println("Hello, World!!!");
    }
}

 
package com.codepumpkin.demo1;
import com.codepumpkin.demo.*;

class B
{
   public static void main(String args[])
      {
          A obj = new A();
          //trying to access public member of class A
          obj.display();
      }
}

Output:

Hello, World!!!

Let's summarize what we discussed till now in the form of the table:

Access Modifier

Some important notes on Access Modifiers:

  • It is important to keep in mind that the Java access modifier assigned to a Java class takes precedence over any access modifiers assigned to fields, constructors, and methods of that class.
  • When you create a subclass of some class, the methods in the subclass cannot have less accessible access modifiers assigned to them than they had in the superclass.
  • While it is not allowed to decrease the accessibility of an overridden method, it is allowed to expand accessibility of an overridden method.

That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.

Happy Learning 🙂

If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.

We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.



About the Author


Coder, Blogger, Wanderer, Philosopher, Curious pumpkin



Tags: , , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.
Total Posts : 124
follow us in feedly

Like Us On Facebook