Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Java Miscellaneous

Advanced Java

Java APIs & Frameworks

Java Useful Resources

Java - Access Modifiers



Java Access Modifiers

The access modifiers in Java are used to specify the scope of the variables, data members, methods, classes, or constructors. These help to restrict and secure the access (or, level of access) of the data.

There are four level of access:

  • 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).

In this tutorial, we will learn about the Java access modifier and their various types along with the examples.

Types of Java Access Modifiers

There are four different types of access modifiers in Java, we have listed them as follows:

  • Default (No keyword required)
  • Private
  • Protected
  • Public
java access modifiers

1. Default Access Modifier

Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.

A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.

Example: Default Access Modifier

Variables and methods can be declared without any modifiers, as in the following examples −

String version = "1.5.1";

boolean processOrder() {
   return true;
}

2. Private Access Modifier

Methods, variables, and constructors that are declared private can only be accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables that are declared private can be accessed outside the class, if public getter methods are present in the class.

Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.

Example 1: Private Access Modifier

The following class uses private access control −

public class Logger {
   private String format;

   public String getFormat() {
      return this.format;
   }

   public void setFormat(String format) {
      this.format = format;
   }
}

Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly.

So, to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value.

Example 2: Private Access Modifier

In this example, the data members and class methods of the Logger class are private. We are trying to access those class methods in another class Main.

class Logger {
  private String format;

  private String getFormat() {
    return this.format;
  }

  private void setFormat(String format) {
    this.format = format;
  }
}

public class Main {
  public static void main(String[] args) {
    // Creating an object 
    Logger log = new Logger();
    // Setting the value
    log.setFormat("Text");
    // Getting the value
    System.out.println(log.getFormat());

  }
}

Output

Main.java:18: error: setFormat(String) has private access in Logger
    log.setFormat("Text");
       ^
Main.java:20: error: getFormat() has private access in Logger
    System.out.println(log.getFormat());
                          ^
2 errors

3. Protected Access Modifier

Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.

Example 1: Protected Access Modifier

The following parent class uses protected access control, to allow its child class override openSpeaker() method −

class AudioPlayer {
   protected boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}

class StreamingAudioPlayer extends AudioPlayer {
   boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}

Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intention is to expose this method to its subclass only, that's why we have used protected modifier.

Example 2: Protected Access Modifier

This example demonstrates the use of protected access modifier.

// Class One
class One {
  protected void printOne() {
    System.out.println("printOne method of One class.");
  }
}

// Inheriting class One on Main
public class Main extends One {
  public static void main(String[] args) {
    // Creating an object of Main class
    Main obj = new Main();

    // Calling printOne() method of class One
    // through the object of Main class
    obj.printOne();
  }
}

Output

printOne method of One class.

4. Public Access Modifier

A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses.

Syntax

The following function uses public access control −

public static void main(String[] arguments) {
   // ...
}

The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class.

Example: Public Access Modifier

This example demonstrates the use of public access modifier.

// Class One
class One {
  public void printOne() {
    System.out.println("printOne method of One class.");
  }
}

public class Main {
  public static void main(String[] args) {
    // Creating an object of class One
    One obj = new One();

    // Calling printOne() method of class One
    obj.printOne();
  }
}

Output

This example demonstrates the use of public access modifier.

Java Access Modifiers and Inheritance

The following rules for inherited methods are enforced −

  • Methods declared public in a superclass also must be public in all subclasses.

  • Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.

  • Methods declared private are not inherited at all, so there is no rule for them.

The following table shows the summary of the accessibility in the same/different classes (or, packages) based on the access modifiers.

java access modifiers - summary

Example

In this example, we've created a class with a private variable age and a variable with default scope as name. Using setter/getter method, we're updating age and getting value and name is updated directly.

public class Puppy {
   private int age;
   String name;

   public Puppy() {      
   }

   public void setAge( int age ) {
      this.age = age;
   }

   public int getAge( ) {
      return age;
   }

   public static void main(String []args) {
      Puppy myPuppy = new Puppy();

      // update age variable using method call
      myPuppy.setAge( 2 );

      // update name directly
      myPuppy.name = "Tommy";
      System.out.println("Age: " + myPuppy.getAge() +", name: " + myPuppy.name );
   }
}

Output

Age: 2, name: Tommy
java_modifier_types.htm
Advertisements