Easy Tutorial
❮ Java Arraylist Size Method For ❯

Java Modifiers

Java provides a variety of modifiers, primarily categorized into two types:

Modifiers are used to define classes, methods, or variables and are typically placed at the beginning of statements. We illustrate this with the following example:

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 Control Modifiers

In Java, access control modifiers can be used to protect access to classes, variables, methods, and constructors. Java supports four different access levels.

The access levels can be summarized in the following table:

Modifier Current Class Same Package Subclasses (same package) Subclasses (different package) Other Packages
public Y Y Y Y Y
protected Y Y Y Y/N (Explanation) N
default Y Y Y N N
private Y N N N N

Default Access Modifier - No Keyword

Variables and methods declared without any access modifier are visible to classes within the same package. Interface variables are implicitly declared as public static final, and interface methods are by default public.

As shown in the example below, variables and methods can be declared without any modifier.

Example

String version = "1.5.1";
boolean processOrder() {
   return true;
}

Private Access Modifier - private

The private access modifier is the most restrictive level. Methods, variables, and constructors declared as private can only be accessed within the class. Classes and interfaces cannot be declared as private.

Variables declared as private can only be accessed outside the class through public getter methods.

The private modifier is primarily used to hide class implementation details and protect class data.

The following class uses the private access modifier:

public class Logger {
   private String format;
   public String getFormat() {
      return this.format;
   }
   public void setFormat(String format) {
      this.format = format;
   }
}

In this example, the format variable in the Logger class is private, so other classes cannot directly access or modify its value. To allow external access, two public methods are defined: getFormat() (returns the value of format) and setFormat(String) (sets the value of format).

Public Access Modifier - public

Classes, methods, constructors, and interfaces declared as public are accessible by any other class.

If public classes that need to access each other are in different packages, the corresponding packages must be imported. Due to inheritance, all public methods and variables of a class are inherited by its subclasses.

The following function uses public access control:

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

The main() method of a Java program must be public; otherwise, the Java interpreter cannot run the class.

Protected Access Modifier - protected

The protected modifier needs to be analyzed from two perspectives:

Interfaces and their member variables and methods cannot be declared as protected. You can refer to the diagram below for demonstration:

Subclasses can access methods and variables declared with the protected modifier, thus protecting unrelated classes from using these methods and variables.

The following parent class uses the protected access modifier, and the subclass overrides the openSpeaker() method of the parent class.

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

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

If the openSpeaker() method is declared as private, then it can only be accessed by the AudioPlayer class.

If the openSpeaker() method is declared as public, then all classes can access it.

If we only want the method to be visible to subclasses of the class it is in, we declare it as protected.

protected is the most difficult Java class member access modifier to understand. For more detailed information, please refer to Java protected Keyword Detailed Explanation.

Access Control and Inheritance

Please note the following rules for method inheritance:


Non-Access Modifiers

To implement additional functionalities, Java also provides several non-access modifiers.

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

The final modifier is used to modify classes, methods, and variables. A final class cannot be inherited, a final method cannot be redefined by an inheriting class, and a final variable is a constant that cannot be modified.

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

The synchronized and volatile modifiers are mainly used for thread programming.

static Modifier

The static keyword is used to declare variables that are independent of any instance of the class. No matter how many objects are instantiated from a class, its static variables are only copied once. Static variables are also known as class variables. Local variables cannot be declared as static variables.

The static keyword is used to declare methods that are independent of any instance of the class. Static methods cannot use non-static variables of the class. Static methods obtain data from the parameter list and then compute that data.

Access to class variables and methods can be directly made using the classname.variablename and classname.methodname format.

The following example illustrates the use of the static modifier to create class methods and class variables.

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("Starting with " +
      InstanceCounter.getCount() + " instances");
      for (int i = 0; i < 500; ++i){
         new InstanceCounter();
          }
      System.out.println("Created " +
      InstanceCounter.getCount() + " instances");
   }
}

The result of running the above example is as follows:

Starting with 0 instances
Created 500 instances

final Modifier

final Variables: Final indicates the "last" or "final" meaning. Once a variable is assigned a value, it cannot be reassigned. An instance variable modified by final must be explicitly assigned an initial value.

The final modifier is often used together with the static modifier to create class constants.

Example

public class Test{
  final int value = 10;
  // Example of declaring constants
  public static final int BOXWIDTH = 6;
  static final String TITLE = "Manager";

  public void changeValue(){
     value = 12; // This will output an error
  }
}

Final Method

A final method in the parent class can be inherited by a subclass but cannot be overridden by the subclass.

The main purpose of declaring a final method is to prevent the content of the method from being modified.

Here is an example of declaring a method with the final modifier.

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

Final Class

A final class cannot be inherited, and no class can inherit any characteristics of a final class.

Example

public final class Test {
   // Class body
}

Abstract Modifier

Abstract Class:

An abstract class cannot be used to instantiate objects; the only purpose of declaring an abstract class is to extend it in the future.

A class cannot be both abstract and final. If a class contains abstract methods, it must be declared as an abstract class, otherwise a compilation error will occur.

An abstract class can contain both abstract and non-abstract methods.

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 that has no implementation; the specific implementation of the method is provided by the subclass.

An abstract method cannot be declared as final or static.

Any subclass inheriting from an abstract class must implement all the abstract methods of the parent class, unless the subclass is also an abstract class.

If a class contains abstract methods, it must be declared as an abstract class. An abstract class does not have to contain abstract methods.

The declaration of an abstract method ends with a semicolon, for example: public abstract sample();.

Example

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

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

Synchronized Modifier

A method declared with the synchronized keyword can only be accessed by one thread at a time. The synchronized modifier can be applied to the four access modifiers.

Example

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

Transient Modifier

When a serialized object contains instance variables modified by transient, the Java Virtual Machine (JVM) skips that specific variable.

This modifier is included in the statement that defines the variable, used to preprocess the data type of the class and variable.

Example

public transient int limit = 55;   // Not persistent
public int b; // Persistent

Volatile Modifier

A member variable declared with volatile is forced to be re-read from shared memory every time it is accessed by a thread. Moreover, when the member variable changes, it forces the thread to write the changed value back to shared memory. This ensures that at any given moment, two different threads always see the same value for a member variable.

A volatile object reference can be null.

Example

public class MyRunnable implements Runnable
{
    private volatile boolean active;
    public void run()
    {
        active = true;
        while (active) // First line
        {
            // Code
        }
    }
    public void stop()
    {
        active = false; // Second line
    }
}

Under normal circumstances, when one thread calls the run() method (initiated by a Runnable thread) and another thread calls the stop() method, if the active value in the buffer is used, the loop will not stop when the active value in the buffer becomes false.

However, in the above code, we have used the volatile keyword to modify active, so the loop will stop.

❮ Java Arraylist Size Method For ❯