Java – Access and Class Modifiers

Modifiers are keywords that you add during initialization to change values. The Java language has a wide range of modifiers, the main ones are:

  • access modifiers;
  • class, method, variable, and stream modifiers not used for access.

To use a modifier in Java, you need to include its keyword in the definition of a class, method, or variable. The modifier must be in front of the rest of the statement, as shown in the following examples:

Java – Access and Class Modifiers

public class className {
    // ...
}
private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main (String [] arguments) {
    // method body
}

Access modifiers

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

  • Visible in package (default and no modifier required).
  • Visible only for the class (private).
  • Visible to all (public).
  • Visible to package and all subclasses (protected).

Default access modifier – no keyword

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

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

Example

Variables and methods can be declared in Java without any modifiers, as shown in the following example:

String version = "1.5.1";

boolean processOrder() {
   return true;
}

Private access modifier

Private modifier – methods, variables and constructors that are declared private in Java can only be accessed within the declared class itself.

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

Variables declared as private can be accessed outside the class if the receiving public methods are present in the class (see below for an example and explanation).

Using the private modifier in Java is the main way to hide data.

Example

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 is no way for other classes to get and set its value directly.

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

Public access modifier

The public modifier is 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 we try to access the public class in another package, then the public class must be imported.

Due to class inheritance, in Java all public methods and variables of a class are inherited by its subclasses.

Example

The following function uses public access control:

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

The main () method must be public. Otherwise, it cannot be called using the java interpreter to run the class.

Protected access modifier

The protected modifier – variables, methods and constructors that are declared protected in a superclass can only be accessed by subclasses in another package or for any class in a protected class package.

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

Protected access gives a subclass the ability to use a helper method or variable, preventing an unrelated class from trying to use it.

Example

The following parent class uses protected access controls so that its child class overrides the openSpeaker () method :

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

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

Moreover, if we define the openSpeaker () method as protected, then it will not be accessible from any other class except AudioPlayer. If we define it as public, then it will become available to everyone. But our intention is to expose this method to the subclass only, which is why we used the protected modifier.

Access control and inheritance rules

The following rules in Java apply for inherited methods:

  • Methods declared public in a superclass must also be public in all subclasses.
  • Methods that are declared protected in a superclass must either be protected or public in their subclasses; they cannot be private.
  • Methods that are declared private are not inherited for everyone, so there is no rule for them.

Class, method, variable, and stream modifiers not used for access

Java provides a number of modifiers not for access but for many other functionalities:

  • the static modifier is used to create methods and class variables;
  • the final modifier is used to complete the implementation of classes, methods and variables;
  • the abstract modifier is required to create abstract classes and methods;
  • the synchronized and volatile modifiers are used in Java for threads.

The static modifier

The static modifier is used to create methods and class variables.

Static variables

The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of a static variable in Java exists, regardless of the number of instances of the class.

Static variables are also known as class variables. In Java, local variables cannot be declared static.

Static methods

The static keyword is used to create methods that will exist independently of any instances created for the class.

In Java, static methods or static methods do not use any instance variables of any class object, they are defined. The static methods take all data from parameters and some of these parameters are evaluated without reference to variables.

Variables and methods of a class can be accessed using the class name followed by a period and the name of the variable or method.

Example

The static modifier in Java is used to create class methods and variables, as shown in the following example:

public class InstanceCounter {

    private static int numInstances = 0;

    protected static int getCount () {
       return numInstances;
    }

    private static void addInstance () {
       numInstances ++;
    }

    InstanceCounter () {
       InstanceCounter.addInstance ();
    }

    public static void main (String [] arguments) {
       System.out.println ("Since" +
       InstanceCounter.getCount () + "instance");
       for (int i = 0; i <500; ++ i) {
          new InstanceCounter ();
}
       System.out.println ("Created" +
       InstanceCounter.getCount () + "instances");
    }
}

You will get the following output:

Starting from 0 instance
Created 500 copies

Final modifier

The final modifier is used to complete the implementation of classes, methods and variables.

Final variables

A final variable can only be initialized once. A reference variable declared final can never be assigned to refer to another object.

However, the data inside the object can be changed. Thus, the state of the object can be changed, but not the reference.

With variables in Java, the final modifier is often used with static to make a class variable a constant.

Example

public class Test {
   final int value = 10;
   // Below are examples of constant declarations:
   public static final int BOXWIDTH = 6;
   static final String TITLE = "Manager";
  
   public void changeValue () {
      value = 12; // an error will be received
   }
}

Final methods

The final method cannot be overridden by any subclass. As mentioned earlier, in Java, the final modifier prevents a method from being changed in the subclass.

The main intent to make the method final is that the content of the method should not be changed to the side.

Example

The declaration of a method using the final modifier in a class declaration is shown in the following example:

public class Test {
     public final void changeName () {
        // method body
     }
}

Final class

The main purpose in Java of using a class declared as final is to prevent the class from being subclassed. If a class is marked final, then no class can inherit any function from the final class.

Example

public final class Test {
    // class body
}

Abstract modifier

The abstract modifier is used to create abstract classes and methods.

Abstract class

The abstract class cannot instantiate. If a class is declared abstract, then its sole purpose is to be extended.

A class cannot be both abstract and final, since a final class cannot be extended. If a class contains abstract methods, then it must be declared abstract. Otherwise, a compilation error will be generated.

An abstract class can contain both abstract methods as well as ordinary ones.

Example

abstract class Caravan {
    private double price;
    private String model;
    private String year;
    public abstract void goFast (); // abstract method
    public abstract void changeColor ();
}

Abstract method

An abstract method is a method declared with any implementation. The body of the method (implementation) is provided by the subclass. Abstract methods can never be final or strict.

Any class that extends an abstract class must implement all the abstract methods of the superclass, unless the subclass is an abstract class.

If a Java class contains one or more abstract methods, then the class must be declared abstract. An abstract class does not have to contain abstract methods.

An abstract method ends with a semicolon. Example: public abstract sample ();

Example

public abstract class SuperClass {
     abstract void m (); // abstract method
}

class SubClass extends SuperClass {
      // implements an abstract method
       void m () {
.........
       }
}

Synchronized modifier

The synchronized modifier is used in Java for threads.

The synchronized keyword is used to indicate that a method can only be accessed by one thread at a time. In Java, the synchronized modifier can be applied with any of the four access level modifiers.

Example

public synchronized void showDetails(){
.......
}

Transient modifier

An instance variable marked as transient instructs the Java virtual machine (JVM) to skip the specified variable when serializing the object that contains it.

This modifier is included in the statement, which creates a variable of the preceding class or data type of the variable.

Example

public transient int limit = 55; // won't persist
public int b; // will persist

Volatile modifier

The volatile modifier is used in Java for threads.

In Java, the volatile modifier is used to let the JVM know that the variable access thread should always concatenate its own copy of the variable with the master copy in memory.

Accessing the volatile variable synchronizes all cached copied variables in memory. Volatile can only be applied to instance variables that are of type object or private. A reference to a volatile object can be null.

Example

public class MyRunnable implements Runnable {
     private volatile boolean active;
 
     public void run () {
         active = true;
         while (active) {// line 1
             // some code here
         }
     }
    
     public void stop () {
         active = false; // line 2
     }
}

Typically, run () is called on one thread (first time using Runnable in Java), and stop () is called from another thread. If line 1 uses a cached active value, then the loop cannot stop until you set active false on line 2.