Core Java (七) Java中的static修飾符

來源:互聯網
上載者:User

static為靜態意思,常用來修飾內部類,方法,變數。

靜態域

static修飾的變數在每個類中只有一個副本,即這個類的所有對象共用一個變數,它屬於類,不屬於任何獨立的對象。

package com.xujin;class Base{protected static int MAX = 100;}public class Another extends Base{public static void main(String[] args){Base base1 = new Base();Base base2 = new Base();Base base3 = new Base();System.out.println(base1.MAX);//100System.out.println(base2.MAX);//100System.out.println(base3.MAX);//100base1.MAX = 10;System.out.println(base1.MAX);//10System.out.println(base2.MAX);//10System.out.println(base3.MAX);//10}}

靜態常量

static final 修飾符,即為常量。

public class Math{...public static final PI = 3.14159265358979323846;...}

Math.PI就可以訪問該常量。

public static final 修飾符很重要,他可以公開給別的類但不允許其他類修改。

靜態方法

static方法是靜態方法,是一種不能向對象實施操作的方法(即沒有隱式的參數this),比如Math.random(),Math.pow(x, a);  

不能在一個static方法內部訪問非static變數,可以通過類名(推薦)和對象名(不推薦)調用這個方法。

靜態方法不能被重寫,一個非static(普通的)方法也不能在子類中重寫為static 方法。另外,一個static方法也不能在子類中重寫為static 方法中,因為重寫必須符合多態性,而static並不符合這個規定。

如下例子:

package com.xujin;class Base{public static void aMethod(){System.out.println("Base a");}public void bMethod(){System.out.println("Base b");}}public class Another extends Base{public static void main(String argv[]){Base so = new Another();Another fo = new Another();so.aMethod();//Base afo.aMethod();//Another aso.bMethod();//Another bfo.bMethod();//Another b}public static void aMethod(){System.out.println("Another a");}public void bMethod(){System.out.println("Another b");}}

其中有一個靜態方法aMethod()和一個非靜態方法bMethod(),bMethod()符合多態性,而靜態方法aMethod()不符合多態性。

所以說這個不屬於方法重寫。

main方法

當啟動程式的時候還沒有任何一個對象,所以靜態main方法將執行並建立程式所需要的對象。

main方法也可以用來對某個類進行單元測試。

靜態內部類

把一個類隱藏在另一個類的內部,內部類不可引用外部類對象,取消了產生的引用。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.