Java modifiers
The Java language provides many modifiers, which are mainly divided into the following two categories:
Access modifiers
Non-access Modifiers
Modifiers are used to define classes, methods or variables, and are usually placed at the front of the statement. We use the following example 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) { // 方法体 }
Access control modifier
In Java, you can use access control modifiers to protect access to classes, variables, methods and constructors. Java supports 4 different access rights.
The default, also called default, is visible within the same package without any modifiers.
Private, specified with the private modifier, visible within the same class.
Public, specified with the public modifier, visible to all classes.
Protected, specified with the protected modifier, visible to classes and all subclasses in the same package.
Default access modifier - do not use any keywords
Variables and methods declared using the default access modifier are visible to classes in the same package. The variables in the interface are implicitly declared as public static final, and the access rights of the methods in the interface are public by default.
Example:
As shown in the following example, variables and methods can be declared without any modifiers.
String version = "1.5.1"; boolean processOrder() { return true; }
Private access modifier-private
Private access modifier is the most restrictive access level, so methods, variables and constructors declared as 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 methods in the class.
The use of Private access modifier is mainly used to hide the implementation details of the class and protect the data of the class.
The following classes use 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 the variable. In order to enable other classes to operate this variable, 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 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 where the corresponding public class is located. Due to class inheritance, 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.
Protected access modifier-protected
Variables, methods and constructors declared as protected can be accessed by any other class in the same package, or by classes in different packages subclass access.
Protected access modifier cannot modify classes and interfaces. Methods and member variables can be declared as protected, but member variables and member methods of interfaces cannot be declared as protected.
Subclasses can access the methods and variables declared by 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 overloads the parent class's openSpeaker() method.
class AudioPlayer { protected boolean openSpeaker(Speaker sp) { // 实现细节 } } class StreamingAudioPlayer { boolean openSpeaker(Speaker sp) { // 实现细节 } }
If the openSpeaker() method is declared as private, classes other than AudioPlayer will not be able to access this method. If openSpeaker() is declared as public, all classes can access this method. If we only want the method to be visible to subclasses of its class, declare the method as protected.
Access control and inheritance
Please note the following rules for method inheritance:
Methods declared as public in the parent class must also be public in the child class.
Methods declared as protected in the parent class are either declared as protected or public in the subclass. Cannot be declared private.
Methods declared as private in the parent class cannot be inherited.
Non-access modifier
In order to achieve some other functions, Java also provides many non-access modifiers.
static modifier, used to create class methods and class variables.
Final modifier is used to modify classes, methods and variables. Classes modified by final cannot be inherited, modified methods cannot be redefined by inherited classes, and modified variables are constants and cannot be modified.
Abstract modifier, used to create abstract classes and abstract methods.
Synchronized and volatile modifiers are mainly used for thread programming.
Static modifier
Static variables:
The Static keyword is used to declare static variables independent of objects, regardless of No matter how many objects a class instantiates, there is only one copy of its static variables. Static variables are also called class variables. Local variables cannot be declared as static variables.
Static method:
The Static keyword is used to declare static methods that are independent of the object. Static methods cannot use non-static variables of the class. Static methods get data from a parameter list and then calculate the data.
Access to class variables and methods can be directly accessed using classname.variablename and classname.methodname.
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("Starting with " + InstanceCounter.getCount() + " instances"); for (int i = 0; i < 500; ++i){ new InstanceCounter(); } System.out.println("Created " + InstanceCounter.getCount() + " instances"); } }
The editing results of the above example are as follows:
Started with 0 instances Created 500 instances
Final modifier
Final variable:
Final variable can be displayed Initialized formally and only once. References to objects declared final cannot point to different objects. But the data in the final object can be changed. In other words, the reference of the final object cannot be changed, but the value inside can be changed.
The Final modifier is usually used together with the static modifier to create class constants.
Example:
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 subclasses, but cannot be modified by subclasses.
The main purpose of declaring a final method is to prevent the content of the method from being modified.
As shown below, use the final modifier to declare the method.
public class Test{ public final void changeName(){ // 方法体 } }
Final class
The Final class cannot be inherited, and no class can inherit any characteristics of the final class.
Instance:
public final class Test { // 类体 }
Abstract modifier
Abstract class:
Abstract class cannot be used to instantiate objects, declare abstract The only purpose of a class is to facilitate future extensions to the class.
A class cannot be modified by abstract and final at the same time. If a class contains abstract methods, the class must be declared as an abstract class, otherwise a compilation error will occur.
Abstract classes can contain abstract methods and non-abstract methods.
Example:
abstract class Caravan{ private double price; private String model; private String year; public abstract void goFast(); //抽象方法 public abstract void changeColor(); }
Abstract method
Abstract method is a method without any implementation. The specific implementation of the method is provided by the subclass. Abstract methods cannot be declared final and strict.
Any subclass that inherits an abstract class must implement all abstract methods of the parent class, 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 does not need 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(); //抽象方法 } class SubClass extends SuperClass{ //实现抽象方法 void m(){ ......... } }
Synchronized modifier
Synchronized keyword The declared method can only be accessed by one thread at a time. The Synchronized modifier can be applied to four access modifiers.
Example:
public synchronized void showDetails(){ ....... }
Transient modifier
When the serialized object contains an instance variable modified by transient, the Java Virtual Machine (JVM) skips the specific variable.
This modifier is included in the statement that defines the variable and is used to preprocess the data type of the class and variable.
Example:
public transient int limit = 55; // will not persist public int b; // will persist
Volatile modifier
Volatile modified member variables are forced to re-read from the shared memory every time they are accessed by a thread. value. Moreover, when a member variable changes, the thread is forced to write the changed value back to the shared memory. In this way, at any time, two different threads always see the same value of a member variable.
A volatile object reference may be null.
Example:
public class MyRunnable implements Runnable { private volatile boolean active; public void run() { active = true; while (active) // 第一行 { // 代码 } } public void stop() { active = false; // 第二行 } }
Normally, the run() method is called on one thread (the thread started by Runnable), and the stop() method is called on another thread. If the active value of the buffer in the first line is used, the loop will not loop when the active value of the second line is false. will stop.
But in the above code we used volatile to modify active, so the loop will stop.