Access modifiers in java

Let’s learn access modifiers in java.

Access modifiers in java

Java access modifiers control the visibility or scope of member variables, class, constructor and methods.

Also read – system array copy

In my previous posts you have seen the use of public, private and protected in creating class or method. These are called as access modifiers.

There are four types of access modifier private, protected, public and default.

private access modifier

If member variables and methods defined with keyword “private”, then it can be accessed / visible within the class.

Also read – class and objects in java

Private access modifiers are restrictive one. Because it restricts the access of variables and methods outside package.

Classes and interfaces should not be defined with “private” keyword. Because classes and interfaces needs access outside the package or within.

class Demo
{
   // java private
   private void displayName()
   {
      System.out.println("Flower Brackets");
   }
}

public class PrivateDemo 
{
   public static void main(String[] args) 
   {
      Demo obj = new Demo();
      obj.displayName();
   }
}



Output:

access modifiers in java

public access modifier

In this case class, method or variable declared with keyword “public” is accessible everywhere or to entire java program.

If we want to access a class which is “public” outside the package then we can “import” that class to particular package.

package a1;

public class Example1
{
   // java public
   public void printName()
   {
      System.out.println("Flower Brackets");
   }
}

package a2;
import a1.*;

public class PublicDemo 
{
   public static void main(String[] args) 
   {
      Example1 obj = new Example1();
      obj.printName();
   }
}



Output:

Flower Brackets


protected access modifier

Member variables and methods declared with keyword “protected” can be accessed within the same package or by subclasses of other package.

// protected java
package abc;
class Demo
{
   // java protected
   protected void printName()
   {
      System.out.println("Hello World");
   }
}

package def;
import abc.*;

class ProtectedExample extends Demo
{
   public static void main (String args[])
   {
      ProtectedExample obj = new ProtectedExample();
      obj.printName();
   }
}



Output:

Hello World


default access modifier in java

Method, member variable or class declared with no access modifier have “default” access modifier.

Variables, class or method having default access modifier are accessible within same package.

// java default access modifier
package abc;
class Demo
{
   void printName()
   {
      System.out.println("Flower Brackets");
   }
}

package def;
import abc.*;

class DefaultExample
{
   public static void main (String args[])
   {
      Demo obj = new Demo();
      obj.printName();
   }
}



Output:

Compile error


Here’s the relationship of above discussed access modifiers in java,

access modifiers in java