JAVA Non Access Modifier|JAVA Tutorials Point
学习完了JAVA的基础知识之后,发现对非访问修饰符的掌握还是很薄弱,不知道有时候该用哪种修饰符,有点搞不清,这篇文章结合中外两种的网站来全面的复习一下。
static 修饰符,用来修饰类方法和类变量。
The static modifier for creating class methods and variables.
静态变量:
static 关键字用来声明独立于对象的静态变量,无论一个类实例化多少对象,它的静态变量只有一份拷贝。 静态变量也被称为类变量。局部变量不能被声明为 static 变量。
静态方法:
static 关键字用来声明独立于对象的静态方法。静态方法不能使用类的非静态变量。静态方法从参数列表得到数据,然后计算这些数据。
The static keyword is used to create variables that will exist independently of any instances created for the class. Only one copy of the static variable exists regardless of the number of instances of the class.
Static variables(静态变量) are also known as class variables. Local variables cannot be declared static.
Static Methods
The static keyword is used to create methods that will exist independently of any instances created for the class.
Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
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");
}
}
final 修饰符,用来修饰类、方法和变量,final 修饰的类不能够被继承,修饰的方法不能被继承类重新定义,修饰的变量为常量,是不可修改的。
The final modifier for finalizing the implementations of classes, methods, and variables.
abstract 修饰符,用来创建抽象类和抽象方法。
The abstract modifier for creating abstract classes and methods.
synchronized 和 volatile 修饰符,主要用于线程的编程。
The synchronized and volatile modifiers, which are used for threads.