Detailed explanation of java modifiers

The Java language provides many modifiers, mainly divided into the following two categories:

  • access modifier
  • non-access modifier

Modifiers are used to define classes, methods or variables and are usually placed at the beginning of a statement. We illustrate with the following example:

1
2
3
4
5
6
7
8
9
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 controllers 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, is visible within the same class.

Common, specified with the public modifier, visible to all classes.

Protected, specified with the protected modifier, visible to the class and all subclasses within the same package.

Default access modifier - no keywords are used

Variables and methods declared with the default access modifier are visible to classes within the same package. The variables in the interface are implicitly declared as public static final, and the methods in the interface are public by default.

Example:

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

?
1
2
3
4
String version = "1.5.1" ;
boolean processOrder() {
   return true ;
}

private access modifier - private

The private access modifier is the most restrictive access level, so methods, variables and constructors declared as private can only be accessed by the owning class, and classes and interfaces cannot be declared private .

Variables declared as private access types can only be accessed by external classes through 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 protect the data of the class.

The following classes use the private access modifier:

1
2
3
4
5
6
7
8
9
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 a private variable, so other classes cannot directly get and set the value of this variable. To enable other classes to manipulate 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 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 classes are 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:

1
2
3
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 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 protected, but interface member variables and member methods cannot be declared protected.

Subclasses can access methods and variables declared with the Protected modifier, thus protecting unrelated classes from using those methods and variables.

The following parent class uses the protected access modifier, and the child class overrides the parent class's openSpeaker() method.

1
2
3
4
5
6
7
8
9
10
class AudioPlayer {
   protected boolean openSpeaker(Speaker sp) {
    // 实现细节
   }
}
class StreamingAudioPlayer {
   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 public, all classes can access this method. If we only want the method to be visible to subclasses of its owning class, declare the method as protected.

Access Control and Inheritance

Note the following rules for method inheritance:

  • A method declared public in the parent class must also be public in the child class.
  • A method declared as protected in the parent class is either declared protected or public in the child class. Cannot be declared private.
  • Methods declared as private in the parent class cannot be inherited.

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. Final modified classes 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 variable:

The Static keyword is used to declare static variables independent of objects. 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 can 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 compute 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 result of running and editing the above example is as follows:

Started with 0 instances
Created 500 instances

Final modifier

Final variable:

Final variables can be explicitly initialized and can only be initialized once. A reference to an object declared final cannot point to a different object. But the data in the final object can be changed. That is to say, the reference of the final object cannot be changed, but the value inside can be changed.

The final modifier is usually used in conjunction with the static modifier to create class constants.

Example:

1
2
3
4
5
6
7
8
9
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.

Declare the method with the final modifier as shown below.

1
2
3
4
5
public class Test{
   public final void changeName(){
     // 方法体
   }
}

Final class

Final class cannot be inherited, no class can inherit any features of final class.

Example:

1
2
3
public final class Test {
   // 类体
}

Abstract modifier

Abstract class:

Abstract classes cannot be used to instantiate objects, and the sole purpose of declaring an abstract class is to extend the class in the future.

A class cannot be abstract and final at the same time. If a class contains abstract methods, the class must be declared abstract, otherwise a compilation error will occur.

抽象类可以包含抽象方法和非抽象方法。

实例:

1
2
3
4
5
6
7
abstract class Caravan{
   private double price;
   private String model;
   private String year;
   public abstract void goFast(); //抽象方法
   public abstract void changeColor();
}

抽象方法

抽象方法是一种没有任何实现的方法,该方法的的具体实现由子类提供。抽象方法不能被声明成final和static。

任何继承抽象类的子类必须实现父类的所有抽象方法,除非该子类也是抽象类。

如果一个类包含若干个抽象方法,那么该类必须声明为抽象类。抽象类可以不包含抽象方法。

抽象方法的声明以分号结尾,例如:public abstract sample();

实例:

1
2
3
4
5
6
7
8
9
public abstract class SuperClass{
   abstract void m(); //抽象方法
class SubClass extends SuperClass{
    //实现抽象方法
    void m(){
      .........
    }
}

Synchronized修饰符

Synchronized关键字声明的方法同一时间只能被一个线程访问。Synchronized修饰符可以应用于四个访问修饰符。

实例:

1
2
3
public synchronized void showDetails(){
.......
}

Transient修饰符

序列化的对象包含被transient修饰的实例变量时,java虚拟机(JVM)跳过该特定的变量。

该修饰符包含在定义变量的语句中,用来预处理类和变量的数据类型。

实例:

1
2
public transient int limit = 55 // will not persist
public int b; // will persist

volatile修饰符

Volatile修饰的成员变量在每次被线程访问时,都强迫从共享内存中重读该成员变量的值。而且,当成员变量发生变化时,强迫线程将变化值回写到共享内存。这样在任何时刻,两个不同的线程总是看到某个成员变量的同一个值。一个volatile对象引用可能是null。

实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
   }
}

一般地,在一个线程中调用run()方法,在另一个线程中调用stop()方法。如果line 1中的active位于缓冲区的值被使用,那么当把line 2中的active设置成false时,循环也不会停止。


转自:http://www.jb51.net/article/100962.htm

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325734710&siteId=291194637