OPEN between Secret

생성자와 this() 를 이용한 예 본문

java/정의

생성자와 this() 를 이용한 예

해가꿈꾸는달 2012. 5. 19. 19:50
반응형


public class Book {

     String title;
     String author;
     int ISBN;
 
 public Book(String title, String author, int ISBN) {
      this.title = title;
      this.author = author;
      this.ISBN = ISBN;
      System.out.println(title + author + ISBN);
 }
 
 public Book(String title, int ISBN) {
      this(title, "Anonymouse" , ISBN);
  
 }
 
 public Book(){
      this(null, null, 0);
      System.out.println("생성자가 호출되었음;");
  
 }
 public static void main(String [] args) {
      Book javaBook = new Book("Java JDK", " 황기태" , 3333);
      Book holyBible = new Book("Holy Bible", 1);
      Book emptyBook = new Book();
     }
}

------------------------------------------------------------

출력시 결과가
-------------------------
Java JDK 황기태3333        |
Holy Bible Anonymouse 1  |
nullnull0                          | 
생성자가 호출되었음;        |
-------------------------

main에 있는 각각의 생성자들을 호출시 this()가 다시 맨 위의 생성자를 다시 호출한다.

this() 의 특징
    1) 생성자코드에서만 사용 가능
    2) 동일한 클래스 내에서 다른 생성자를 호출할때 사용
    3) 무조건 생성자의 첫번째 문장에서 사용되어야 함 

반응형

'java > 정의' 카테고리의 다른 글

오버로딩(overloading) 과 오버라이딩 (overriding)  (0) 2012.05.30
메소드 오버라이딩이란  (0) 2012.05.28
상속과 생성자  (0) 2012.05.28
f inal 키워드란  (0) 2012.05.26
접근 지정자  (0) 2012.05.22