abstract
用于定义抽象方法。抽象方法仅具有签名(方法名、参数与返回值),需进一步覆盖使用。包含抽象方法的类称为抽象类,同样需要添加 abstract 修饰符。继承抽象类时必须覆盖其中所有的抽象方法。interface 指令也起到了抽象的功能,因此常省略重复使用 abstract。
abstract class AnAbstractClass{
abstract void anAbstractMethod();
}
static
用于定义静态成员(字段或方法)。静态成员无需实例化即可访问。
public class AStaticClass{
static String aStaticField= "This is a static field.";
static void aStaticMethod() {
System.out.println("This is a static method.");
}
public static void main(String[] args) {
System.out.println(AStaticClass.aStaticField);
AStaticClass.aStaticMethod();
}
}
final
final 方法无法覆盖、final 字段无法再次赋值、final 类无法被继承。
final class AFinalClass {
final int aFinalField = 0;
final void aFinalMethod() {
}
}
transient
transient 对象不会被序列化。有时,为了将对象通过网络传输或存入数据库,需要将序列化(如将其转换为字节数组形式)。对于一些临时变量,或其他一些特殊原因,可通过 transient 修饰符是成员免于序列化。
class MyClass implements Serializable {
private String aSerializableString;
private transient String aTemporaryString; // 该字符串不会被序列化
}
volatile
多线程处理中,各线程的成员将各自分配缓存。volatile 修饰符强制所有线程中的成员共用同一缓存,共享相同的值。
class MyClass {
volatile int shareValue;
}
synchronized
synchronized 修饰符使成员无法被多个线程同时访问,必须依次进行(同步处理)。如果方法分属不同实例,synchronized 将无法确保处理同步。
class MyClass {
synchronized void synchronizedProcess() { }
}
native
native 修饰符表示方法由非 Java 语言实现,因此,方法体将被省略。随着 Java 性能的改善,native 的应用范围也逐渐缩小。
public native int hashCode();
strictfp
strictfp 修饰符要求程序严格遵循 IEEE 754 标准对浮点小数进行计算。此时,不同环境中浮点数运算的误差不复存在,但处理速度将有所下降。
strictfp double val;