Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java modifier


May 10, 2021 Java


Table of contents


Java modifier

The Java language provides a number of modifiers, mainly in the following two categories:

  • Access modifiers
  • Non-access modifier

Modifiers are used to define classes, methods, or variables, usually at the front of a statement. L et's 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) {
   // 方法体
}

Access control modifier

In Java, you can use access controls to protect access to classes, variables, methods, and construction methods. Java supports 4 different access rights.

The default, also known as default, is visible within the same package and does not use any modifiers.

Private, specified by the private modifier, is visible within the same class.

Common, specified by the public modifier, is visible to all classes.

Protected, specified by the protected modifier, is visible to classes and all sub-classes within the same package.

Default access modifier - no keywords are used

Variables and methods declared by the default access modifier are visible to classes within the same package. V ariables in the interface are implicitly declared public static final while methods in the interface have access to public

Instance:

As the following example shows, variables and method declarations can be made without any modifiers.

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

Private access modifier-private

Private access modifiers are the most restrictive access levels, so methods, variables, and construction methods that are declared private can only be accessed by the class to which they belong, and classes and interfaces cannot be declared private.

Variables declared as private access types can only be accessed by external classes through the public getter method in the class.

Private access modifiers are used primarily to hide the implementation details of the class and to protect the class's data.

The following class uses a private access modifier:

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

In an instance, the format variable in the Logger class is a private variable, so other classes cannot get and set the value of the variable directly. T o enable other classes to manipulate the variable, two public are getFormat() (returns the value of the form) and setFormat(String) (set the value of the form)

Public access modifier-public

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

If several public classes that access each other are distributed in different packages, you need to import the package in which the public class is located. B ecause of the inheritance of a class, all public methods and variables of a class can be inherited by its children.

The following functions use public access control:

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

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

Protected access modifier-protected

Variables, methods, and constructors declared as protected can be accessed by any other class in the same package, as well as by sub-classes in different packages.

The Protected access modifier cannot modify classes and interfaces, methods and member variables can be declared as protected, but member variables and member methods of the interface cannot be declared as protected.

Subses have access to methods and variables declared by the Protected modifier, which protects unrelated classes from using them.

The following parent class uses a protected access modifier, and the child class overloads the parent class's openSpeaker() method.

class AudioPlayer {
   protected boolean openSpeaker(Speaker sp) {
      // 实现细节
   }
}

class StreamingAudioPlayer {
   boolean openSpeaker(Speaker sp) {
      // 实现细节
   }
}

If you declare the openSpeaker() method as private, classes other than AudioPlayer will not be able to access the method.

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

If we only want the method to be visible to the sub-classes of the class in which it is located, declare the method as protected.

Access control and inheritance

Note the rules inherited by the following methods:

  • Methods declared as public in the parent class must also be public in child classes.

  • Methods declared as protected in the parent class are either declared as protected or public in the child class. Cannot be declared private.

  • Methods declared as private in the parent class can not be inherited.


Non-access modifier

For some other functionality, Java also provides many non-access modifiers.

Static modifier, which is used to create class methods and class variables.

Final modifier, used to modify classes, methods, and variables, final modified classes can not be inherited, modified methods can not be redefined by inherited classes, modified variables are constant, can not be modified.

Abstract modifier to create abstract classes and abstract methods.

synchronized and volatile modifiers, primarily used for thread programming.

static modifier

  • Static variables:

    The static keyword is used to declare static variables that are object-independent, with only one copy of a static variable, regardless of how many objects a class instantiates. S tatic variables are also known as class variables. L ocal variables cannot be declared static variables.

  • Static method:

    The static keyword is used to declare static methods that are independent of objects. S tatic methods cannot use non-static variables of classes. S tatic methods get data from a list of parameters and then calculate the data.

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

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

The above example runs the edit as follows:

Started with 0 instances
Created 500 instances

Final modifier

Final variable:

The final variable can be explicitly initialized and can only be initialized once. R eferences to objects declared final cannot point to different objects. H owever, the data in the final object can be changed. That is, the reference to the final object cannot be changed, but the value inside can be changed.

Final modifiers are typically used with static modifiers to create class constants.

Instance:

public class Test{
  final int value = 10;
  // 下面是声明常量的实例
  public static final int BOXWIDTH = 6;
  static final String TITLE = "Manager";

  public void changeValue(){
     value = 12; //将输出一个错误
  }
}

Final method

The Final method in a class can be inherited by a sub-class, but it cannot be modified by a sub-class.

The primary purpose of declaring the final method is to prevent its contents from being modified.

Use the final modifier declaration method, as shown below.

public class Test{
    public final void changeName(){
       // 方法体
    }
}

The final class

The final class cannot be inherited, and no class can inherit any attributes of the final class.

Instance:

public final class Test {
   // 类体
}

abstract modifier

Abstract class:

Abstract classes cannot be used to instantiate objects, and the sole purpose of declaring abstract classes is to expand them in the future.

A class cannot be decorated by both abstract and final. I f a class contains abstract methods, the class must be declared abstract or there will be a compilation error.

Abstract classes can contain abstract and non-abstract methods.

Instance:

abstract class Caravan{
   private double price;
   private String model;
   private String year;
   public abstract void goFast(); //抽象方法
   public abstract void changeColor();
}

Abstract methods

An abstract method is a method that does not have any implementation, and the concrete implementation of the method is provided by a sub-class. A bstract methods cannot be declared as final and static.

Any child class that inherits an abstract class must implement all abstract methods of the parent class, unless the child class is also an abstract class.

If a class contains several abstract methods, the class must be declared as abstract. A bstract classes can not contain abstract methods.

The declaration of an abstract method ends with a sign, e.g. public abstract sample();

Instance:

public abstract class SuperClass{
    abstract void m(); //抽象方法
}
 
class SubClass extends SuperClass{
     //实现抽象方法
      void m(){
          .........
      }
}

Synchronized modifier

Methods declared by the synchronized keyword can only be accessed by one thread at a time. S ynchronized modifiers can be applied to four access modifiers.

Instance:

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

transient modifier

When a serialized object contains an instance variable modified by transient, the java virtual machine (JVM) skips that particular variable.

The modifier is contained in the statement that defines the variable and is used to preprocess the data types of classes and variables.

Instance:

public transient int limit = 55;   // will not persist
public int b; // will persist

Volatile modifier

The volatile modified member variable forces the value of the member variable to be reread from shared memory each time it is accessed by a thread. A lso, when member variables change, the thread is forced to write the change value back to shared memory. This way, at any moment, two different threads always see the same value for a member variable.

A volatile object reference may be null.

Instance:

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

Typically, the run() method is called in one thread and the stop() method in another thread. I f the value of active in line 1 in the buffer is used, the loop does not stop when the active in line 2 is set to false.