English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I)/O)

Java Reader/Writer

Java Other Topics

Java Modifiers

Java provides many modifiers, mainly divided into the following two categories:

  • Access modifier

  • Non-access modifiers

Modifiers are used to define classes, methods, or variables and are usually placed at the beginning of a statement. We use the following examples to illustrate:

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 modifier

In Java, access control modifiers can be used to protect access to classes, variables, methods, and constructors. Java supports 4 types of access permissions.

  • default (i.e., default, nothing written): Visible within the same package without using any modifiers. Used for: classes, interfaces, variables, methods.

  • private : Visible within the same class. Used for: variables, methods. Note: Cannot be used to modify classes (external classes)

  • public : Visible to all classes. Used for: classes, interfaces, variables, methods

  • protected : Visible to classes within the same package and all subclasses. Used for: variables, methods. Note: Cannot be used to modify classes (external classes).

We can use the following table to explain access permissions:

Access control

ModifierCurrent classSame packageSubclasses (in the same package)Subclasses (in different packages)Other packages
publicYYYYY
protectedYYYY/N(Description)N
defaultYYYNN
privateYNNNN

default access modifier-Without using any keywords

Variables and methods declared with the default access modifier are visible to classes within the same package. Variables in interfaces are implicitly declared as public static final, and methods in interfaces have public access rights by default.

As shown in the following example, the declaration of variables and methods can be made without any modifiers.

package defaultPackage;
class Logger {
    void message(){
        System.out.println("This is a message");
    }
}

In this case, the Logger class has a default access modifier. And this class is visible to all classes in the defaultPackage package. However, if we try to use the Logger class in another class outside of defaultPackage, we will get a compilation error.

private access modifier-private

The private access modifier is the strictest access level, so it is declared as private methods, variables, and constructors can only be accessed by the class they belong to, and classes and interfaces cannot be declared as private.

Variables declared as private access type can only be accessed by external classes through public getter methods within the class.

The use of the private access modifier is mainly used to hide the implementation details of the class and protect the 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 the example, the format variable in the Logger class is a private variable, so other classes cannot directly get and set the value of this variable. In order to allow other classes to operate this variable, two public methods are defined: getFormat() (returning the value of format) and setFormat(String) (setting the value of format).

Public access modifier-public

Classes, methods, constructors, and interfaces declared as public can be accessed by any other class.

If several public classes that are mutually accessible are distributed in different packages, you need to import the package where the corresponding public class is located. Due to the inheritance of classes, all public methods and variables of a class can be inherited by its subclasses.

The following functions use public access control:

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

The main() method of the Java program must be set to public, otherwise, the Java interpreter will not be able to run the class.

The protected access modifier-protected

protected needs to be analyzed and explained from the following two points:

  • The subclass and the superclass are in the same packageDeclared as protected variables, methods, and constructors can be accessed by any other class in the same package;

  • The subclass and the superclass are not in the same packageSo in the subclass, the subclass instance can access the protected methods inherited from the base class, but cannot access the protected methods of the base class instance.

protected can modify data members, constructors, method members,Cannot be used to modify classes (except for inner classes)..

Interface members and member variables and methods cannot be declared as protected.

The subclass can access methods and variables declared with the protected modifier, thereby protecting unrelated classes from using these methods and variables.

The superclass uses the protected access modifier, and the subclass overrides the superclass's openSpeaker() method.

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

If openSpeaker() method is declared as private, then classes other than AudioPlayer cannot access the method.

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

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

protected is the most difficult to understand of the Java class member access permission modifiers.

Access control and inheritance

Please note the following rules of method inheritance:

  • Methods declared as public in the superclass must also be public in the subclass.

  • Methods declared as protected in the superclass must be declared as protected or public in the subclass, and cannot be declared as private.

  • Methods declared as private in the superclass cannot be inherited.

Non-access modifiers

To implement other functions, Java also provides many non-access modifiers.

static modifier, used to modify class methods and class variables.

final modifier, used to modify classes, methods, and variables. The class cannot be inherited if it is declared as final, the method cannot be redefined by the inheriting class, and the variable is a constant that cannot be modified.

abstract modifier, used to create abstract classes and abstract methods.

synchronized and volatile modifiers, mainly used for thread programming.

static modifier

  • Static variables:

    The static keyword is used to declare static variables that are independent of objects, and regardless of how many objects a class instantiates, its static variables have only one copy. Static variables are also known as class variables. Local variables cannot be declared as static variables.

  • Static methods:

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

Access to class variables and methods can be directly used classname.variablename and classname.methodname to access.

As shown in the following example, the static modifier is used 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("From ", +
      InstanceCounter.getCount() + "instances start");
      for (int i = 0; i < 500; ++i){
         new InstanceCounter();
          }
      System.out.println("Created ", +
      InstanceCounter.getCount() + "instances");
   }
}

The running result of the above example is as follows:

Starting from 0 instances
Create 500 instances

Final modifier

Final variables:

Final means 'final, ultimate', once a variable is assigned a value, it cannot be reassigned. The example variables that are final must be explicitly assigned an initial value.

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

public class Test{
  final int value = 10;
  // The following is an 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

Final methods in the superclass can be inherited by subclasses, but cannot be overridden by subclasses.

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

As shown below, a method is declared using the final modifier.

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

Final class

Final classes cannot be inherited; no class can inherit any characteristics of a final class.

public final class Test {
   // Class body
}

The 'abstract' modifier

Abstract class:

Abstract classes cannot be used to instantiate objects; the sole purpose of declaring an abstract class is to expand it in the future.

A class cannot be decorated with both 'abstract' and 'final' at the same time. 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 methods and non-abstract methods.

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

Abstract method

Abstract methods are methods with no implementation, and their specific implementation is provided by subclasses.

Abstract methods cannot be declared as 'final' and 'static'.

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

If a class contains several abstract methods, then the class must be declared as an abstract class. An abstract class can also not contain abstract methods.

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

public abstract class SuperClass{
    abstract void m(); //Abstract method
}
 
class SubClass extends SuperClass{
     //Implement abstract methods
      void m(){
          .........
      }
}

synchronized modifier

The 'synchronized' keyword declares a method that can only be accessed by one thread at a time. The 'synchronized' modifier can be applied to four access modifiers.

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

transient modifier

When a serialized object contains a variable marked with 'transient', the Java Virtual Machine (JVM) skips this specific variable.

This modifier is included in the statement of defining variables and is used to preprocess the data type of classes and variables.

public transient int limit =; 55;   // Does not persist
public int b; // Persistence

volatile modifier

The member variable decorated with 'volatile' is always re-read from the shared memory when accessed by a thread. Moreover, when the member variable changes, the thread is forced to write the changed value back to the shared memory. This ensures that at any given moment, two different threads always see the same value of a member variable.

A volatile object reference may be null.

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
    }
}

In most cases, a thread calls the run() method (in a thread started by Runnable), and another thread calls the stop() method. If First line If the active value in the buffer is used, then in Second line The loop will not stop when the active value is false.

However, in the above code, we used the volatile modifier for active, so the loop will stop.