Latest web development tutorials

Java modifiers

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

  • Access modifier
  • Non-access modifier

Modifier used to define the class, method or variable, usually at the forefront of the statement. Through the following example to illustrate:

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

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

By default, also known as the default, visible inside the same package, do not use any modifier.

Private, to private modifier is specified, visible within the same class.

There are, in order to specify the public modifier, visible to all classes.

Protected, to protected modifier specifies that, for all classes and subclasses within the same package visible.

The default access modifier - do not use any keywords

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

Example:

Statement in the following example, variables and methods can not use any modifier.

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

Private access modifier -private

Private access modifier is the most stringent level of access, it is declared as private methods, variables, and belongs to the class constructor can only be accessed, and the classes and interfaces can not be declared private.

Variables declared as private access type can only be accessed outside the class through class public getter method.

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

The following classes use the private access modifier:

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

Example, Logger class format variable is a private variable, so other classes can not directly get and set the value of the variable. In order to be able to operate the other class variable defines two public methods: getFormat () (return value format) and setFormat (String) (setting the format)

Public access modifier -public

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

If several mutual visits of public classes in different packages, you need to import the appropriate package public class resides. Because inheritance class, the class of all public methods and variables can be inherited by its subclasses.

The following functions use the public access control:

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.

Protected access modifiers -protected

Is declared as protected variables, methods and constructors in the same package can be any other type of access, and can be accessed in different packages subclasses.

Protected access modifier can not be modified classes and interfaces, methods, and member variables can be declared as protected, but the member variables and member methods of interfaces can not be declared protected.

Subclasses can access modifier is declared Protected methods and variables, so that we can protect the unrelated classes using these methods and variables.

The following parent class uses protected access modifier, subclasses override openSpeaker () method of the parent class.

class AudioPlayer {
   protected boolean openSpeaker(Speaker sp) {
      // 实现细节
   }
}

class StreamingAudioPlayer {
   boolean openSpeaker(Speaker sp) {
      // 实现细节
   }
}

If openSpeaker () method is declared as private, then in addition to AudioPlayer class can not access the method. If openSpeaker () is declared as public, then all classes are able to access the method. If we want to make the process visible to the subclasses of the class, then the method is declared as protected.

Access control and inheritance

Please note the following methods inherited rules:

  • Parent class declared as public methods in the subclass must also be public.

  • Parent class declared as protected method in a subclass or declared as protected, either declared as public. You can not be declared private.

  • Parent class declared as private method can not be inherited.


Non-access modifier

In order to achieve a number of other features, Java also provides a number of non-access modifiers.

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

Final modifier, used to decorate classes, methods and variables, final modified class can not be inherited, the modified method of the class can not be inherited redefined, modified variables constant, can not be modified.

Abstract modifier used to create abstract classes and abstract methods.

Synchronized and volatile modifiers, mainly for programming threads.

Static modifier

  • Static variables:

    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 declare an object is independent of the static method. Static methods can not use non-static variables class. Static method to get the data from the parameter list, and then calculate the data.

Access to class variables and methods can be used directly classname.variablename and classname.methodname of access.

In the following example, 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");
   }
}

Examples of the above editing operation results are as follows:

Started with 0 instances
Created 500 instances

Final qualifier

Final variables:

Final variables can be explicitly initialized and initialized only once. Reference is declared as final objects can not point to a different object. But the final target where the data can be changed. That final reference object can not be changed, but the value of which can be changed.

Final modifier is usually used together to create a static modifier class constant.

Example:

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

Final class methods inherited by subclasses, but can not modify the subclasses.

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

As shown below, using the final declaration modifier methods.

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

Final category

Final classes can not be inherited, no class can inherit any of the characteristics of the final class.

Example:

public final class Test {
   // 类体
}

Abstract modifier

Abstract class:

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

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, a compiler error.

An abstract class may 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();
}

Abstract method

No method is an abstract method implementation, the specific implementation of the method provided by subclasses. Abstract methods can not be declared as final and strict.

Any subclass inherits the abstract class must implement all abstract methods of the parent class, 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 can not contain abstract methods.

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

Example:

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

Synchronized modifier

Method Synchronized keyword to declare the same time only one thread access. Synchronized modifier can be applied to the four access modifiers.

Example:

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

Transient modifier

Serialized object contains modified by transient instance variables, java virtual machine (JVM) to skip that particular variable.

The modifier is included in the definition of variables statement for preprocessing data type classes and variables.

Example:

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

Volatile Modifiers

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 the member variable changes, a thread is forced to change the value written back to the shared memory. So that 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) // 第一行
        {
            // 代码
        }
    }
    public void stop()
    {
        active = false; // 第二行
    }
}

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

However, the above code, we use a modified volatile active, so the cycle will stop.