java建構函式使用方法總結

來源:互聯網
上載者:User

使用構造器時需要記住:

 

1.構造器必須與類同名(如果一個源檔案中有多個類,那麼構造器必須與公用類同名)

2.每個類可以有一個以上的構造器

3.構造器可以有0個、1個或1個以上的參數

4.構造器沒有傳回值

5.構造器總是伴隨著new操作一起調用

 

樣本:

A.java

 

 

Java代碼  
  1. public class A{  
  2.    public A(){  
  3.       System.out.println("調用了無參的建構函式");  
  4.    }  
  5.    public A(String mess){  
  6.       System.out.println("調用了有參的建構函式\n"+  
  7.          "參數內容為:"+mess);  
  8.    }  
  9. }  

 Test.java

 

Java代碼  
  1. public class Test{  
  2.    public static void main(String [] args){  
  3.        A a_1=new A();//調用無參的建構函式  
  4.        A a_2=new A("Hello");//調用有參的建構函式  
  5.    }  
  6. }  

 輸出結果:

 

繼承與建構函式

 

使用super調用父類構造器的語句必須是子類構造器的第一條語句

如果子類構造器沒有顯式地調用父類的構造器,則將自動調用父類的預設(沒有參數)的構造器。如果父類沒有不帶參數的構造器,並且在子類的構造器中又沒有顯式地調用父類的構造器,則java編譯器將報告錯誤

 

樣本:

 

A.java

Java代碼  
  1. public class A{  
  2.    public A(){  
  3.       System.out.println("調用了A的無參建構函式");  
  4.    }  
  5.    public A(String mess){  
  6.       System.out.println("調用了A的有參的建構函式\n"+  
  7.          "參數內容為:"+mess);  
  8.    }  
  9. }  

 

B.java

Java代碼  
  1. public class B extends A{  
  2.    public B(){  
  3.       System.out.println("調用了B的無參建構函式");  
  4.    }  
  5.    public B(String mess){  
  6.       super(mess);  
  7.       System.out.println("調用了B的有參建構函式\n"+  
  8.          "參數內容為:"+mess);  
  9.    }  
  10. }  

 

Test.java

Java代碼  
  1. public class Test{  
  2.    public static void main(String [] args){  
  3.        B b_01=new B();  
  4.        B b_02=new B("你好");  
  5.    }  
  6. }  

 

輸出結果:

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.