Java學習筆記----main

來源:互聯網
上載者:User

標籤:java學習筆記 main

1.java中main方法是程式的入口方法,main還是必須的兩個修飾符是public和static.舉例

A:public static void main(String args[])B:public static final void main(String args[])C:static public void main(String args[])D:static public synchronized void main(String args[])E:static public abstract void main(String args);


上面可以是入口main方法的只有ABCD.

2.同一個java檔案當中可可以有多個main方法舉例

class T{public static void  main(String agrs[]){System.out.println("T mian");}}public class Test{public static void main(String args[]){System.out.println("Test main");}}


運行結果:Test main

運行結果表明:只有和檔案名稱相同的類裡面的main方法才是程式的入口方法,即Test.java中只有名為Test類中的main是程式的入口,同時一個java檔案中可以有多個main方法。


3.在main方法前輸出HelloWorld

public class Test{static {System.out.println("hello world1");}public static void main(String args[]){System.out.println("hello world2");}}


運行結果是:hello world1

     hello world2

public class Test{public static void main(String args[]){System.out.println("hello world2");}        static {System.out.println("hello world1");}}



這段程式和上面的程式輸出結果一樣。因此表明在程式運行時,靜態塊是在main方法之前被載入的,而且static塊在程式中的位置無關。


4.java程式的初始化順序

(1)靜態對象(變數)優先於非靜態對象(變數)初始化,靜態對象(變數)只初始化一次,非靜態可能會初始化多次。、

(2)父類優先於子類進行初始化

(3)按照成員變數的定義順序進行初始化

class B extends Object{static{System.out.println("static B");}public B(){System.out.println("constructor B");}}class A extends B{static{System.out.println("static A");}public A(){System.out.println("constructor A");}}public class Test{public static void main(String args[]){new A();}}


執行結果:

static B

static A

constructor B

constructor A



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java學習筆記----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.