2016-09-25 358 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(); 

至极将调用地址的构造函数不带参数。

相关问题