Java modifiers knowledge consolidation

Java modifiers


Java language provides a number of modifiers, divided into the following categories:

  • Access modifier
  • Non-access modifier

Modifiers used to define classes, methods, or variables, typically on the most distal end statement.

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) {
   // 方法体
}

First, the access control modifier

Java can be used to control access to secure access to character classes, variables, methods, and constructors. Java supports four different access rights.

  • default (which is the default, nothing to write): Visible in the same package, do not use any modifier. Using objects: classes, interfaces, variables, methods.
  • Private : Visible within the same class. Use objects: variables and methods. Note: You can not modify the class (outside class)
  • public : visible to all classes. Using objects: classes, interfaces, variables, methods
  • protected : visible to all classes and subclasses in the same package. Use objects: variables and methods. Note: You can not modify the class (outside class) .
Modifiers The current class The same intracapsular Descendant class (same package) Descendant class (in different packages) Other packages
public Y Y Y Y Y
protected Y Y Y Y / N N
default Y Y Y N N
private Y N N N N

Second, the default access modifier - do not use keywords

Use variables and methods declared in default access modifier for class in the same package is visible. The interface where the variables are implicitly declared as public static final, and the interface in the default access method is public by default.

Examples shown in the following statement, variables and methods may be used without any modifier.

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

Third, private access modifier -private

Private access modifier is used primarily for data protection and the implementation details of the class behind class.

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

Fourth, the public access modifier -public

It is declared as public classes, methods, constructors, and interfaces can be any other type of access.

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

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

Fifth, non-access modifiers

static modifier for modification of class variables and class methods.

final modifier for modifying classes, variables and methods, a modified final class can not be inherited, a modified method of the class can not be inherited redefined, the modified variables constant, can not be modified.

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

synchronized and volatile modifier, mainly for programming thread.

1, static modifier

  • Static variables:

    The static keyword is used to declare static variables independent of the object, no matter how many objects a class is instantiated, it is only one copy of a static variable. Static variables also known as class variables. Local variables can not be declared as static variables.

  • Static methods:

    static keyword is used to separate the object of a static method declaration. Static methods can not use non-static variables class. Static method to get the data from the parameter list, the data is then calculated.

Access to class variables and methods can be used as the class name. Variable names and class names. Method name mode access.

Example:

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");
   }
}
---结果:
Starting with 0 instances
Created 500 instances

2, final qualifier

final variable:

final represents the "last, final" after meaning, once the variable assignment, can not be reassigned. The modified final instance variables must be explicitly specified initial value.

The final modifier and static modifier is usually used together to create a class constants.

public class Test{
  final int value = 10;
  // 下面是声明常量的实例
  public static final int BOXWIDTH = 6;
  static final String TITLE = "Manager";
 
  public void changeValue(){
     value = 12; //将输出一个错误
  }
}

final Methods:

final method in the parent class can be inherited by subclasses, but can not be overridden by subclasses.

The main purpose of the method is to prevent the final declaration of this method is modified.

As shown below, using the methods declared final modifier.

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

final categories:

final class can not be inherited, no class can inherit any properties of final class.

public final class Test {
   // 类体
}

3, abstract modifier

Abstract class:

An abstract class can not be used to instantiate an object, the sole purpose of the statement of an abstract class is the class for future expansion.

A class can not be modified abstract and final. If a class contains abstract methods, the class must be declared as an abstract class, otherwise the compilation error will occur.

An abstract class may contain a non-abstract methods and abstract methods.

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

Abstract methods:

Abstract no method is a method of implementation, the specific implementation of the method provided by subclasses.

Abstract methods can not be declared as final or static.

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

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

Abstract method declarations end with a semicolon, for example: public abstract Sample (); .

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

4, synchronized modifier

The method of synchronized keyword to declare the same time can only be one thread access. synchronized modifier can be applied to four access modifiers.

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

5, transient modifier

When serialized object contains instance variables is transient modification, java virtual machine (JVM) to skip that particular variable.

The modifier is included in the statement defines variables, and classes for pre-processing the data type of the variable.

public transient int limit = 55;   // 不会持久化
public int b; // 持久化

6, volatile modifier

volatile modified member variable each time it is accessed threads are forced to re-read the value of the member variable from shared memory. Also, when members of the variable changes, a thread is forced to change the value written back to the shared memory. So that at any moment, two different threads always see the same value of a member variable.

A volatile object reference may be null.

public class MyRunnable implements Runnable
{
    private volatile boolean active;
    public void run()
    {
        active = true;
        while (active) // 第一行
        {
            // 代码
        }
    }
    public void stop()
    {
        active = false; // 第二行
    }
}

Under normal circumstances, a thread calls the run () method (in the open Runnable threads), in another thread calls stop () method. If the first line of active value in the buffer is used, then the second row cycle does not stop when the active is false.

But the above code we use volatile modification active, so the cycle will stop.

发布了10 篇原创文章 · 获赞 9 · 访问量 1322

Guess you like

Origin blog.csdn.net/qq_43658155/article/details/104806815