Home > Java > javaTutorial > body text

Detailed explanation of Java modifiers

高洛峰
Release: 2017-01-24 15:27:16
Original
1171 people have browsed it

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

Access modifiers

Non-access modifiers

Modifiers are used to define classes, Methods or variables are usually placed at the front of the statement. We use 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) {
  // 方法体
}
Copy after login

Access control modifier

In Java, you can use access control modifiers 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, visible within the same 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 - do not use any keywords

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

Example:

As shown in the following example, variables and methods can be declared without any modifiers.

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

Private access modifier-private

Private access modifier is the most restrictive 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 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 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:

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

In the example, the format variable in the Logger class is a private variable, so other classes cannot directly get and set the value of the variable. In order to enable other classes to operate 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 as 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 class is 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:

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

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, or by classes in different packages subclass access.

Protected access modifier cannot modify classes and interfaces. Methods and member variables can be declared as protected, but member variables and member methods of interfaces cannot be declared as protected.

Subclasses can access the methods and variables declared by the Protected modifier, thus protecting 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) {
   // 实现细节
  }
}
class StreamingAudioPlayer {
  boolean openSpeaker(Speaker sp) {
   // 实现细节
  }
}
Copy after login

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

Access control and inheritance

Please 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 private.

Methods declared as private in the parent class cannot be inherited.

Non-access modifier

In order to achieve some other functions, Java also provides many non-access modifiers.

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

Final modifier is used to modify classes, methods and variables. Classes modified by final 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 variables:

The Static keyword is used to declare static variables that are independent of objects. No matter how many objects a class instantiates, its static variables are only A copy. 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 that are independent of the object. Static methods cannot use non-static variables of the class. Static methods get data from a parameter list and then calculate the data.

Access to class variables and methods can be directly accessed 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");
  }
}
Copy after login


The above instance running editing results are as follows:

Started with 0 instances
Created 500 instances

Final modifier

Final variable:

Final变量能被显式地初始化并且只能初始化一次。被声明为final的对象的引用不能指向不同的对象。但是final对象里的数据可以被改变。也就是说final对象的引用不能改变,但是里面的值可以改变。

Final修饰符通常和static修饰符一起使用来创建类常量。

实例:

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

Final方法

类中的Final方法可以被子类继承,但是不能被子类修改。

声明final方法的主要目的是防止该方法的内容被修改。

如下所示,使用final修饰符声明方法。

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

Final类

Final类不能被继承,没有类能够继承final类的任何特性。

实例:

public final class Test {
  // 类体
}
Copy after login

Abstract修饰符

抽象类:

抽象类不能用来实例化对象,声明抽象类的唯一目的是为了将来对该类进行扩充。

一个类不能同时被abstract和final修饰。如果一个类包含抽象方法,那么该类一定要声明为抽象类,否则将出现编译错误。

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

实例:

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

抽象方法

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

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

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

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

实例:

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

Synchronized修饰符

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

实例:

public synchronized void showDetails(){
.......
}
Copy after login

Transient修饰符

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

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

实例:

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

volatile修饰符

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

实例:

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
  }
}
Copy after login

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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持PHP中文网!

更多详解Java修饰符相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!