static關鍵字的做用?

Java Language Specification, 3rd 寫道

8.4.3.2 static Methodsapp

A method that is declared static is called a class method. A class method is always invoked without reference to a particular object. An attempt to reference the current object using the keyword this or the keyword super or to reference the type parameters of any surrounding declaration in the body of a class method results in a compile-time error. It is a compile-time error for a static method to be declared abstract.this

A method that is not declared static is called an instance method, and sometimes called a non-static method. An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.對象

15.8.3 thisci

The keyword this may be used only in the body of an instance method, instance initializer or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.作用域

static修飾的變量和方法是獨立於對象而存在的,不產生副本,能夠直接用類名來調用。

一.static修飾的變量

static修飾的變量當且僅當類被加載時初始化。而非static變量在實例化對象時被初始化,產生多個副本,多個對象不互相影響。it

局部變量不能被static修飾io

static不改變變量和方法的做用域,其做用域只受四個訪問修飾符的影響class

二.static修飾的方法

被static修飾的方法內部不能調用非static的變量和方法,非static方法內部能夠調用static變量的方法和變量。import

三.static修飾的代碼塊

static修飾的代碼塊在且只在類被加載時執行一次。變量

執行順序:static代碼塊優於構造塊,優於構造方法。

總結

  1. static class, 聲明靜態內部類;
  2. static field, 聲明靜態成員變量;
  3. static method, 聲明靜態成員方法;
  4. static {...}, 聲明靜態代碼塊;
  5. import static package, 聲明靜態成員變量可見.
相關文章
相關標籤/搜索