Java修饰符/关键字

修饰符分类:

  • 权限修饰符:public、protected、default、private
  • 其他修饰符:abstract、static、final、transient、volatile、native、synchronized、strictfp

public:

  • public的使用对象:public可以修饰 类、抽象类、接口,还可以修饰 方法和变量
  • public修饰的对象可以被所以其他类访问

protected:

  • protected的使用对象:protected可以修饰 方法和变量,不能修饰类(外部类) ,内部类较特殊,后面单独研究。
  • protected修饰的对象可以被 同一包内的类或它的子类所访问

default:

  • default的使用对象:default可以修饰 类、抽象类、接口,还可以修饰 方法和变量
  • default修饰的对象可以被 同一包下的类访问

private:

  • private的使用对象:private可以修饰 方法和变量,不能修饰类(外部类)
  • private修饰的对象只在该类内部可见,外部不可访问,包括他的子类也不能访问、不能覆盖

换个角度看:

  • 类、抽象类、接口可以被public、default修饰,default修饰的类、抽象类、接口只本包内可见
  • 方法和变量可以被public、protected、default、private所有权限修饰符修饰

Q&A:

  • Q:为什么类不能被private、protected修饰?
  • A:private好理解,private的类完全孤立不能为外界所访问,毫无用处;就类而言如果被protected修饰时等价于default,其他的包的类根本无法引用它而产生子类

abstract:

  • abstract用于修饰 类、接口或方法
  • abstract修饰的类即抽象类不能初始化,含未实现即abstract的方法
  • 所有的接口默认是abstract的,当然也可以显示用abstract修饰

final:

  • final用于修饰 类、变量或方法
  • final类不能被继承、final变量不能被修改、final方法不能被覆盖
  • final变量必须初始化,可以在声明时或构造函数里面赋值
  • final变量如果是引用变量,变量的value可变,但不能给引用重新赋值(新对象)
  • final变量如果同时被static修饰,那必须在声明时初始化,不能放到构造函数
  • 构造函数里面调用的方法最好是final的
  • Oracle Tutorial: http://docs.oracle.com/javase/tutorial/java/IandI/final.html
class FinalTest{
    private final List foo = new ArrayList();//

    public FinalTest()
    {
        //foo = new ArrayList(); 如果声明时没有初始化,可以在这里初始化
    }
    
    public void updateFoo(){
        foo.add( new String() );//可以改变被应用对象的值
        //foo = new ArrayList(); //编译错误,不能赋予新的对象
    }
}

static:

  • static可修饰 变量、方法、代码块、内部类,不能修饰外部类
  • static的变量或方法属于具体的类,而不是某个实例,所有实例共享该变量或方法,实例可以改变static变量,也可以通过类名直接调用
  • static的方法不能直接访问 实例变量或方法,static方法里面也不能使用this

transient:

  • 理解transient之前需要先理解序列号serialization
  • What is serialization?
    • 序列化是将对象状态持久化的一个过程,这里的持久化即将一个对象被转化成stream of bytes并存到文件中。反之,我可以从bytes里面deserialization一个对象。要实现这个功能类或接口必须继承Serialization接口
      • Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes and stored in a file. In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. For that purpose, every class or interface must implement the Serialization interface. It is a marker interface without any methods.
  • What is the transient keyword and it’s purpose?
    • 默认情况下,序列化会保存对象的所有变量,如果你不想对象被持久化,你可以把它声明为transient。
      • By default, all of object's variables get converted into a persistent state. In some cases, you may want to avoid persisting some variables because you don't have the need to persist those variables. So you can declare those variables as transient. If the variable is declared as transient, then it will not be persisted. That is the main purpose of the transient keyword.
  • Example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class NameStore  implements Serializable {
    private String firstName;
    private transient String middleName;
    private String lastName;

    public NameStore (String fName, String mName, String lName) {
        this.firstName = fName;
        this.middleName = mName;
        this.lastName = lName;
    }

    public void func(){
        System.out.println("I'm func");
    }
    
    public String toString() {
        StringBuffer sb = new StringBuffer(40);
        sb.append("First Name : ");
        sb.append(this.firstName);
        sb.append("Middle Name : ");
        sb.append(this.middleName);
        sb.append("Last Name : ");
        sb.append(this.lastName);
        return sb.toString();
    }
}

public class TransientExample {
    public static void main(String args[]) throws Exception {
        NameStore nameStore = new NameStore("Steve", "Middle", "Jobs");
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
                "nameStore"));
        // writing to object
        o.writeObject(nameStore);
        o.close();

        // reading from object
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(
                "nameStore"));
        NameStore nameStore1 = (NameStore) in.readObject();
        nameStore1.func();
        System.out.println(nameStore1);
    }
    /**Output
    *
    *I'm func
    *First Name : SteveMiddle Name : nullLast Name : Jobs
    *
    ***/
}

native:

  • 标识一个方法将会用其他语言实现而不是Java,It works together with JNI(Java Native Interface)
  • Native方法曾经主要用于写一些对性能要求很高的代码块,随之Java变得越来越快,Native方法变得不常用了,Native method is currently needed when
    • 调用其他语言写的library
    • 你需要访问那些Java不可及的系统资源,只能Native方法调用其他语言实现
  • Native的方法就像Abstract的方法一样没有方法体。

strictfp:

  • Strictfp ensures that you get exactly the same results from your floating point calculations on every platform. If you don't use strictfp, the JVM implementation is free to use extra precision where available.
  • From the JLS:
    • Within an FP-strict expression, all intermediate values must be elements of the float value set or the double value set, implying that the results of all FP-strict expressions must be those predicted by IEEE 754 arithmetic on operands represented using single and double formats. Within an expression that is not FP-strict, some leeway is granted for an implementation to use an extended exponent range to represent intermediate results; the net effect, roughly speaking, is that a calculation might produce "the correct answer" in situations where exclusive use of the float value set or double value set might result in overflow or underflow.
  • In other words, it's about making sure that Write-Once-Run-Anywhere actually means Write-Once-Get-Equally-Wrong-Results-Everywhere.
  • With strictfp your results are portable, without it they are more likely to be accurate.

volatile:

http://stackoverflow.com/questions/106591/do-you-ever-use-the-volatile-keyword-in-java

synchronized:

 

posted @ 2014-09-04 23:36  ibalintha  阅读(873)  评论(0编辑  收藏  举报