The Java language provides many modifiers, which are mainly divided into the following two categories:
Modifiers are used to define classes, methods or variables, and are usually placed at the front of the statement. We illustrate this through 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) { // 方法体}
In Java, access controls can be used 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 and does not use 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, is visible to classes and all subclasses in the same package.
Variables and methods declared with default access modifiers are visible to classes in the same package. Variables in the interface are implicitly declared as public static final
, while methods in the interface have access permissions of 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; }
The 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 as 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 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 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)
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.
Variables, methods, and constructors declared as protected can be accessed by any other class in the same package, or by subclasses in different packages.
Protected access modifiers cannot modify classes and interfaces. Methods and member variables can be declared protected, but member variables and member methods of interfaces cannot be declared protected.
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 parent class's openSpeaker() method.
class AudioPlayer { protected boolean openSpeaker(Speaker sp) { // 实现细节} } class StreamingAudioPlayer extends AudioPlayer { boolean openSpeaker(Speaker sp) { // 实现细节} }
If the openSpeaker() method is declared 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.
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.
In order to implement some other functions, Java also provides many non-access modifiers.
static modifier, used to create class methods and class variables.
The 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.
The synchronized and volatile modifiers are mainly used for thread programming.
Static variables:
The static keyword is used to declare static variables that are independent of objects. No matter how many objects a class instantiates, there is only one copy of its static variables. Static variables are also known as class variables. Local variables cannot be declared as static variables.
Static method:
The static keyword is used to declare static methods independent of objects. 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 running the above example are as follows:
Started with 0 instances Created 500 instances
final variables:
Final variables can be initialized explicitly 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 often 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; //将输出一个错误} }
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 contents of the method from being modified.
As shown below, declare the method using the final modifier.
public class Test{ public final void changeName(){ // 方法体} }
Final classes cannot be inherited, and no class can inherit any characteristics of a final class.
Example:
public final class Test { // 类体}
Abstract class:
Abstract classes cannot be used to instantiate objects. The only purpose of declaring an abstract class is to extend the class in the future.
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(); }
An 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 static.
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(){ ......... } }
The method declared with the synchronized keyword can only be accessed by one thread at the same time. The Synchronized modifier can be applied to four access modifiers.
Example:
public synchronized void showDetails(){ ....... }
When the serialized object contains an instance variable that is modified by transient, the Java Virtual Machine (JVM) skips that particular 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
Each time a volatile-modified member variable is accessed by a thread, the value of the member variable is forced to be reread from the shared memory. 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) // line 1 { // 代码} } public void stop() { active = false; // line 2 } }
Generally, the run() method is called in one thread and the stop() method is called in another thread. If the value of active in line 1 in the buffer is used, then the loop will not stop when active in line 2 is set to false.