2016-09-25 355 views
0

我想了解構造函數是如何工作的,並提出了兩個問題。我有兩個班,一個是地址,另一個是一個人。 Person類有兩個Address對象。下面是我在做什麼一個簡單的例子:什麼時候在嵌套類中調用構造函數(Java)

private class Person{ 
    private String name; 
    private Address unitedStates; 
    private Address unitedKingdom; 
    Person() 
    { 
    this.name = "lary" 
    } 

    Person(String n) 
    { 
    this.name = n; 
    //Can I call Address(string, string) here on unitedStates and unitedKingdom? 
    } 

        }//end of person class 
private class Address{ 
    private String street; 
    private String country; 

    Address() 
    { 
    this.street = "1 Washington sq"; 
    this.country = "United States"; 
    } 
    Address(String s, String c) 
    { 
    this.street = s; 
    this.country = c; 
    } 

}  
} 

如果我離開的人()的是,它會自動填寫UnitedStates的和unitedKindom的值「1華盛頓平方米」?

而且

我可以傳遞參數的,我留在了例子註釋Address對象?

+2

不;它將是空的。 – SLaks

+0

值將在調用構造函數時設置,但在Person()中,您從不調用構造函數,因此值將爲null。你可以在你留下評論的地方調用構造函數,我試過了。 – passion

回答

1

對象的字段將始終自動設置爲默認值(如果未自行初始化)。該值取決於字段的數據類型(請參見https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)。表示對象的字段的默認值是null。 由於您未初始化字段unitedStatesunitedKingdom,因此它們的值將爲null。你可以做的是初始化Person構造函數中的字段:

Person() 
{ 
    this.name = "lary"; 
    this.unitedStates = new Address(); 
    this.unitedKingdom = new Address(); 
} 

Person(String n) 
{ 
    this.name = n; 
    this.unitedStates = new Address("myStreet", "myCountry"); 
    this.unitedKingdom = new Address(); 
} 

你也可以在另一個使用一個構造函數中的參數this。請注意,我添加了由其他構造函數調用的第三個構造函數:

Person(String n, Address unitedStates, Address unitedKingdom) 
{ 
    this.name = n; 
    this.unitedStates = unitedStates; 
    this.unitedKingdom = unitedKingdom; 
} 

Person(String n) 
{ 
    this(n, new Address("myStreet", "myCountry"), new Address()); 
} 

Person() 
{ 
    this("lary", new Address(), new Address()); 
} 
+0

這幫助我理解了很多!謝謝 –

+0

沒問題。請點擊綠色複選標記接受我的回答;) – user

-1

地址字段剛剛初始化爲空。你必須爲它分配一個地址例如,在用戶構造例如,像

unitedStates = new Adress(); 

至極將調用地址的構造函數不帶參數。

相關問題