2016-09-25 2 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; 
    } 

}  
} 

나는 사람()와 같은, 그것은 자동으로 "1 워싱턴 스퀘어"로 미국 에선 및 unitedKindom에 대한 값을 채울 것입니다두면?

그리고

은 내가 예에서 그 글을 남겼 주소 개체에 대한 인수를 전달할 수 있습니까?

+2

아니요; 그것은 null이됩니다. – SLaks

+0

값은 생성자가 호출 될 때 설정되지만,'Person()'에서는 절대 생성자를 호출하지 않으므로 값은'null'이됩니다. 그리고 당신은 코멘트를 남긴 생성자를 호출 할 수 있습니다. – passion

답변

1

개체의 필드는 사용자가 직접 초기화하지 않으면 항상 기본값으로 자동 설정됩니다. 값은 필드의 데이터 유형에 따라 다릅니다 (여기 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html 참조). 개체를 나타내는 필드의 기본값은 null입니다. unitedStatesunitedKingdom 필드를 초기화하지 않았으므로 값은 null이됩니다. 당신이 할 수있는 Person 생성자 내부의 필드를 초기화 할 수 있습니다 : 당신은 또한 키워드 this과 또 다른 하나의 생성자를 사용할 수

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(); 
} 

. 다른 생성자에서 호출하는 세 번째 생성자를 추가했음을 유의하십시오.

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

주소 필드는 null로 초기화됩니다. 예를 들어 사용자 생성자에서 Address 인스턴스에 할당해야합니다 (예 :

).
unitedStates = new Adress(); 

매개 변수없이 Address 생성자를 호출합니다.

관련 문제