Learn java access modifiers

Hey guys!! Welcome to flower brackets blog. Today we will learn java access modifiers.

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

Also read – system array copy

Access modifiers defines the visibility of member variables and methods within the package or outside the package.

Types of access modifiers

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

private access modifier

If member variables, constructors and methods is defined with keyword “private”, then it can’t be accessed / visible outside the class.

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

To access these variables and methods outside the class we need to use “public getter” methods.

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

public class Employee
{
   // private variable 
   private String name;
   public int id;
   // this method returns the value of name
   public String getName()
   {
      return this.name;
   }
   // this method sets its value
   public void setName(String name)
   {
      this.name = name;
   }
}


public access modifier

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

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

public class Employee
{ 
   public String name;
   public int id;
}


protected access modifier

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

Like private access modifier, classes and interfaces can’t be declared with keyword “protected”.

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

package def;
import abc.*;

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

Output:

Hello World


default access modifier

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

Default access modifier is accessible within same package.

package abc;
class Demo
{
   void print()
   {
      System.out.println("Flower Brackets");
   }
}

package def;
import abc.*;

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

Output:

Compile error


Here’s the relationship of above discussed access modifiers,

Learn Java Access Modifiers

Related Posts