2012-05-14 23 views
-4

我無法掌握那些構造函數的用法。如何知道用戶定義的默認構造函數和用戶定義的參數化構造函數的用法java

據我所知,一個是如下:

public book(){ 
private string author; 
private string title; 
private int reference; 
} 

而一個parametrised構造如下:

public book(string author, string title, int reference){ 
} 

但是怎麼會變成這樣可以在main方法中使用?

+0

的第一個片段是不是有效的Java。第二個定義了一個方法,而不是構造函數。請谷歌爲「Java教程」和閱讀基本的東西。 –

+0

這似乎是手冊可以解決的問題:http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html – MaddHacker

+0

我已將它們更改爲構造函數...我相信? – Banned

回答

1

有三種方式,你可以有一個構造函數:

1)您聲明一個無參數的一個

public class book 
{ 
    string author; 
    string title; 
    int reference; 
    public book() { 
    // initialize member variables with default values 
    // etc. 
    } 
} 

2)您聲明一個帶參數

public class book 
{ 
    string author; 
    string title; 
    int reference 
    public book(string author, string title, int reference) { 
    // initialize member variables based on parameters 
    // etc. 
    } 
} 

3)你讓編譯器爲你聲明一個 - 這要求你不要聲明你自己的聲明。在這種情況下,成員變量將根據它們的類型(基本上它們的無參數構造函數調用)提供默認值。

可以混合選項1)和2),但3)是獨立的(不能混合它與其他任何兩個)。您也可以有參數超過一個構造函數(參數類型/號碼必須是不同的)

一個例子使用:

public static void main(String[] args) { 
    String author = ...; 
    String title = ...; 
    int ref = ...; 
    book book1 = new book(); // create book object calling no-parameter version 
    book book2 = new book(author, title, ref); // create book object calling one-parameter 
           // (of type String) version 
} 
1

Pro的語法,如何使用它們...

 
book b1 = new book(); 
book b2 = new book("My Title", "My Author", 0); 

你叫的第一個創建一個空的書。可能還有setTitle(String title),setAuthor(String author)和setReference(int ref)方法。這看起來像......

 
book b1 = new book(); 
// do stuff to get title author and reference 
b1.setTitle(title); 
b1.setAuthor(author); 
b1.setReference(reference); 

你會打電話給這一個,如果你沒有足夠的標題,作者,和參考提供當你構建書實例。

相關問題