Java language provides many modifiers, mainly divided into the following two categories:
Modifiers are used to define classes, methods, or variables, and are usually placed at the front end of a statement. Let's use the following examples to illustrate:
public class 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 controls can be used to protect access to classes, variables, methods and constructors. Java supports 4 different access permissions.
The default, also known as default, is visible within the same package without using any modifiers.
Private, specified with the private modifier, visible within the same class.
Common, specified by the public modifier, visible to all classes.
Protected, specified with the protected modifier, visible to classes and all subclasses within the same package.
Default access modifier - no keywords are used
Variables and methods declared by default access modifiers are visible to classes within the same package. All variables in the interface are implicitly declared as public static final, while the methods in the interface are public by default.
Example:
As shown in the following example, the declaration of variables and methods can be without any modifiers.
String version = "1.5.1";boolean processOrder() { return true;}Private access modifier - private
Private access modifiers are the strictest 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 type can only be accessed by external classes through 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 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 the example, the format variable in the Logger class is a private variable, so other classes cannot directly obtain and set the value of the variable. To enable other classes to manipulate the 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 are accessing each other are distributed in different packages, you need to import the package where the corresponding public class is located. Due to the inheritance of the class, all public methods and variables of the class can be inherited by its subclasses.
The following functions use public access control:
public static void main(String[] arguments) { // ...}The main() method of a 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 subclasses in different packages.
The Protected access modifier cannot modify classes and interfaces. Methods and member variables can be declared as protected, but the member variables and member methods of the interface cannot be declared as protected.
Subclasses can access methods and variables declared by the Protected modifier, so that they can protect 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) { // Implementation details}}class StreamingAudioPlayer { boolean openSpeaker(Speaker sp) { // Implementation details}}If the openSpeaker() method is declared as private, then 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 want the method to be visible only to a subclass of the class it is located in, then declare the method as protected.
Access control and inheritance
Please note the following inheritance rules:
Non-access modifier
To implement some other functions, Java also provides many non-access modifiers.
The static modifier is used to create class methods and class variables.
Final modifier is used to modify classes, methods and variables. The class modified by final cannot be inherited, the method modified cannot be redefined by the inherited class, and the variable modified is a constant 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
The Static keyword is used to declare static variables independent of objects. No matter how many objects a class instantiates, it has only one copy of its static variable. Static variables are also called class variables. Local variables can be declared as static variables.
Static keyword is used to declare static methods independent of objects. Static methods cannot use non-static variables of the class. The static method gets the data from the parameter list and then calculates the data.
Access to class variables and methods can be accessed directly 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 above examples are run and edited as follows:
Started with 0 instances
Created 500 instances
Final modifier
Final variables:
Final variables can be explicitly initialized and can only be initialized once. References to objects declared as final cannot point to different objects. But the data in the final object can be changed. In other words, the reference to the final object cannot be changed, but the value inside can be changed.
Final modifiers are usually used together with static modifiers to create class constants.
Example:
public class Test{ final int value = 10; // Below is an example declaring a constant public static final int BOXWIDTH = 6; static final String TITLE = "Manager"; public void changeValue(){ value = 12; //An error will be output}}Final method
The Final method in the class can be inherited by the subclass, but cannot be modified by the subclass.
The main purpose of declaring a final method is to prevent the content of the method from being modified.
As shown below, declare the method using the final modifier.
public class Test{ public final void changeName(){ // method body}}Final class
Final classes cannot be inherited, and no class can inherit any features of final classes.
Example:
public final class Test { // class body}Abstract modifier
Abstract class:
Abstract classes cannot be used to instantiate objects. The only purpose of declaring abstract classes is to expand 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(); //Abstract method public abstract void changeColor();}Abstract Methods
An abstract method is a method without any implementation, and the specific implementation of the method is provided by a subclass. Abstract methods cannot be declared as 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, the class must be declared as an abstract class. Abstract classes may not 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
The method declared by 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(){......}Transient modifier
When a serialized object contains a transient-modified instance variable, the java virtual machine (JVM) skips that specific variable.
This modifier is included in a statement that defines a variable and is used to preprocess the data types of classes and variables.
Example:
public transient int limit = 55; // will not persistpublic int b; // will persist
volatile modifier
Volatile modified member variables are forced to reread the value of the member variable from shared memory each time they are accessed by a thread. Moreover, when the member variable changes, the thread is forced to write the change value back to shared memory. In this way, at any moment, two different threads always see the same value of a certain 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 { // Code} } 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 in line 1's active in the buffer is used, the loop will not stop when the active in line 2 is set to false.
The above is all the content of this article. I hope that the content of this article will be of some help to everyone’s study or work. I also hope to support Wulin.com more!