2016-08-19 5 views
-1

저는 생성자에서 'this'키워드를 연습하고 있습니다. "this"가 생성자를 명시 적으로 호출하는 데 도움이된다는 것을 알게되었습니다. 그러나 실시간으로 그것의 사용은 무엇입니까.명시 적 생성자 호출 사용

명시 적 생성자 호출.

class JBT { 

    JBT() { 
     this("JBT"); 
     System.out.println("Inside Constructor without parameter"); 
    } 

    JBT(String str) { 
     System.out 
       .println("Inside Constructor with String parameter as " + str); 
    } 

    public static void main(String[] args) { 
     JBT obj = new JBT(); 
    } 
} 
+5

은'그러나 당신은 당신이 실제로 당신을 여기 모르거나 무엇을 원하는 것을 명확히 수있는 실제 time.'에서의 사용 무엇인가 이해하기가 힘들어? – SomeJavaGuy

답변

0

this 현재 인스턴스/객체에 대한 참조를 반환 String 인수 생성자를 호출

Inside Constructor with String parameter as JBT 
Inside Constructor without parameter 

this("JBT") 때문이다. 당신은 당신이 슈퍼 키워드를 사용할 수 있습니다 기본 클래스 또는 수퍼 클래스의 생성자를 호출 할 경우

글쎄, 당신은 같은 클래스의 다른 생성자에서 하나의 생성자를 호출하기 위해이 키워드를 사용할 수 있습니다. 다른 하나의 생성자를 Java로 생성자 체인이라고합니다.

예 :

public class ChainingDemo { 
    //default constructor of the class 
    public ChainingDemo(){ 
     System.out.println("Default constructor"); 
    } 
    public ChainingDemo(String str){ 
     this(); 
     System.out.println("Parametrized constructor with single param"); 
    } 
    public ChainingDemo(String str, int num){ 
     //It will call the constructor with String argument 
     this("Hello"); 
     System.out.println("Parametrized constructor with double args"); 
    } 
    public ChainingDemo(int num1, int num2, int num3){ 
    // It will call the constructor with (String, integer) arguments 
     this("Hello", 2); 
     System.out.println("Parametrized constructor with three args"); 
    } 
    public static void main(String args[]){ 
     //Creating an object using Constructor with 3 int arguments 
     ChainingDemo obj = new ChainingDemo(5,5,15); 
    } 
} 

출력 :

실제 생활에서
Default constructor 
Parametrized constructor with single param 
Parametrized constructor with double args 
Parametrized constructor with three args 
1

, 당신은 대부분 (당신이 당신의 예에서처럼) 기본 값을 설정하는 데 사용하도록 사용자에 대한 클라세의 인터페이스를 단순화 할 수 있습니다.

시간이 지남에 따라 클래스가 발전하고 몇 가지 새로운 기능을 추가 할 때 매우 자주이 작업이 필요합니다. 이것을 고려하십시오 :

// First version of "Test" class 
public class Test { 
    public Test(String someParam) { 
     ... 
    } 
} 

// use of the class 
Test t = new Test("Hello World"); // all is fine 

를 지금, 나중에, 당신은 그래서 당신은 생성자 변경, 테스트에 새로운 멋진 전환 기능을 추가 할 : 이제

public Test(String someParam, boolean useCoolNewFeature) 

을 원래의 클라이언트 코드는 것이다 더 이상 컴파일하지 않습니다. 입니다. 당신은 또한 이전 constructure 서명을 제공하는 경우

그러나, 모두가 잘 될 것입니다 :

public Test(String someParam) { 
    this(someParam, false); // cool new feature defaults to "off" 
} 
관련 문제