Detail the Java modifier

  • 2020-05-26 08:24:29
  • OfStack

The Java language provides a number of modifiers, which fall into two main categories:

Access modifier Non-access modifier

Modifiers are used to define a class, method, or variable, usually at the front of a statement. Here's an 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) {
  //  Method body 
}

Access control modifier

In Java, you can use access control characters to protect access to classes, variables, methods, and constructors. Java supports four different access rights.

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

Private, specified with the private modifier, visible in the same 1 class.

Common, 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 - no keywords are used

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 to public by default.

Example:

Variables and methods can be declared without any modifiers, as shown in the following example.


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

Private access modifier -private

Private access modifiers are the strictest level of access, 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 the Private access modifier is mainly used to hide the implementation details of the class and to protect the data of the class.

The following classes use private access modifiers:


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

In the instance, the format variable in the Logger class is private, so other classes cannot directly get and set the value of the variable. To enable other classes to manipulate this variable, two public methods are defined: getFormat(), which returns the value of format, and setFormat(String), which sets the value of format.

Public access modifier -public

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

If several of the public classes accessed by each other are distributed in different packages, you need to import the package in which the corresponding public class resides. Because of 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, as well as 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 an interface cannot be declared as protected.

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

The parent class below USES the protected access modifier, and the subclass overrides the openSpeaker() method of the parent class.


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

If you declare the openSpeaker() method as private, it will not be accessible to classes other than AudioPlayer. If openSpeaker() is declared as public, then all classes can access the method. If we want the method to be visible only to subclasses of its class, we declare the method as protected.

Access control and inheritance

Note the following rules for method inheritance:

Methods declared as public in the parent class must also be public in the subclass. Methods declared as protected in the parent class are either declared as protected or public in the subclass. Cannot be declared as private. Methods declared as private in a parent class cannot be inherited.

Non-access modifier

For some other purposes, Java also provides a number of non-access modifiers.

The static modifier is used to create class methods and class variables.

The Final modifier is used to modify classes, methods and variables. The class modified by final cannot be inherited, and the modified method cannot be redefined by the inherited class. The modified variable is a constant and cannot be modified.

The Abstract modifier is used to create abstract classes and abstract methods.

The Synchronized and volatile modifiers are used primarily for programming threads.

Static modifier

Static variables:

The Static keyword is used to declare static variables that are independent of objects, and that have only one copy of the static variable, no matter how many objects a class instantiates. Static variables are also called class variables. Local variables can be declared as static variables.

Static method:

The Static keyword is used to declare static methods independent of the object. A static method cannot use a class's non-static variables. The static method gets the data from the parameter list and then computes 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 editing results of the above example are as follows:

Started with 0 instances
Created 500 instances

Final modifier

Final variables:

The Final variable can be explicitly initialized and can be initialized only once. A reference to an object declared as final cannot point to a different object. But 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.

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

Example:


public class Test{
 final int value = 10;
 //  Here is an example of declaring a constant 
 public static final int BOXWIDTH = 6;
 static final String TITLE = "Manager";
 public void changeValue(){
   value = 12; // The output 1 A mistake 
 }
}

Final method

The Final method in a class can be subclassed, but cannot be modified by subclasses.

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

Declare the method using the final modifier, as shown below.


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

Final class

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

Example:


public final class Test {
  //  The class body 
}

Abstract modifier

An 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, class 1 must be declared as an abstract class, otherwise a compilation error will occur.

An abstract class can contain both abstract and non-abstract methods.

Example:


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

Abstract methods

An abstract method is a method that does not have any implementation, the concrete implementation of which is provided by a subclass. Abstract methods cannot be declared as final and strict.

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

If a class contains several abstract methods, the class must be declared an abstract class. An abstract class may not contain abstract methods.

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

Example:


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

Synchronized modifier

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

Example:


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

Transient modifier

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

This modifier is contained in the statement that defines the variable and is used to preprocess the data types of the class and the variable.

Example:


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

volatile modifier

The member variable modified by Volatile is forced to reread the value of the member variable from Shared memory each time it is accessed by a thread. Also, when a member variable changes, the thread is forced to write the change back to Shared memory. In this way, at any given moment, two different threads will always see the same value of a member variable. An volatile object reference might 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
  }
}

1. Call the run() method in one thread and the stop() method in another thread. If the value active in line 1 is used in the buffer, the loop will not stop when active in line 2 is set to false.


Related articles: