[JAVA] 생성자
[JAVA] 생성자
생성자 왜 쓸까?
- 객체를 자동으로 초기화 해주기 위해
- 중복을 줄이고 초기화 로직을 모아서 관리 가능
- 객체를 다양하게 초기화 가능 (오버로딩)
1
2
3
4
5
6
7
//생성자 O
Book book = new Book("Hello Java", "Seo");
//생성자 X
Book book = new Book();
book.name = "Hello Java";
book.author = "Seo";
this()
- 객체 내부에서 자신의 참조값을 가르킬때 사용
1
2
3
4
5
6
7
8
public class Book {
String title;
Book(String title) {
this.title = title; // 왼쪽은 필드, 오른쪽은 매개변수
//x001.title = "Hello Java";
}
}
✅
this 를 제거하면 title은 둘다 매개변수를 뜻하게 된다. 따라서 값이 변경되지 않음
생략가능
- 필드이름과 매개변수의 이름이 다르면 생략이 가능함
1
2
3
4
5
6
7
8
public class Book {
String title;
Book(String titleName) {
title = titleName; // 왼쪽은 필드, 오른쪽은 매개변수
//x001.title = "Hello Java";
}
}
✅
요즘 트렌드는 필요한 곳에만
this.
를 쓰고, 불필요하면 생략해서 코드 간결하게 유지하는 방향
this() 규칙
- this는 생성자 코드의 첫줄에만 작성할 수 있다.
- 한 객체가 생성될 때 어떤 생성자가 먼저 실행되는지 혼란 없이 명확하게 하기 위해서
1
2
3
4
Book(String title, String author) {
System.out.print("아 방정리 해야하는데");
this(title, author, 0)
}
✅
this가 생성자 첫번째 줄에 없으면 컴파일 에러가 발생한다.
1
2
3
4
Book(String title, String author) {
this(title, author, 0); // 반드시 첫 줄에 있어야 함!
System.out.println("방정리는 나중에...");
}
기본 생성자
1
2
3
4
5
6
7
public class Book {
String title;
public Book() {
// 기본 생성자
}
}
- 매개변수 없음
- 직접 만들 수 있음
- 다른 생성자가 있으면 Java에서 자동으로 만들어줌
- 생성자가 하나라도 있으면 기본 생성자를 만들지 않음
오버로딩(Overloading)과 this()
오버로딩(Overloading)이란?
이름은 같지만, 매개변수(의 개수, 타입, 순서)가 다른 메서드나 생성자를 여러 개 정의하는 것
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Book {
String title;
String author;
int page;
//매개변수가 없는 기본 생성자 page 초기화는 0
Book() {
this.title = "";
this.author = "";
}
//매개변수를 2개 받는 생성자
Book(String title, String author) {
this.title = title;
this.author = author;
this.page = 0;
}
//매개변수를 다 받는 생성자
Book(String title, String author, int page) {
this.title = title;
this.author = author;
this.page = page;
}
void display() {
System.out.println("title = " + title +
" author = " + author + " page = " + page);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class BookMain {
public static void main(String[] args) {
//기본 생성자 사용
Book book1 = new Book();
book1.display();
//title과 author만을 매개변수로 받는 생성자
Book book2 = new Book("JAVA의 정석", "남궁성");
book2.display();
//모든 필드를 매개변수로 받는 생성자
Book book3 = new Book("은노기의 JSP", "김은옥", 789);
book3.display();
}
}
1
2
3
4
출력결과:
title = author = page = 0
title = JAVA의 정석 author = 남궁성 page = 0
title = 은노기의 JSP author = 김은옥 page = 789
this()를 이용한 생성자 연결
this는 생성자 내부에서 자신의 생성자를 호출할 수 있다. 즉 자신의 생성자를 호출!
방금 book 프로그램을 리펙토링 해보자
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Book {
String title;
String author;
int page;
Book() {
this("","",0);
}
Book(String title, String author) {
this(title, author, 0)
}
//최종 목적지
Book(String title, String author, int page) {
this.title = title;
this.author = author;
this.page = page;
}
void display() {
System.out.println("title = " + title +
" author = " + author + " page = " + page);
}
}
1
2
3
4
출력결과:
title = author = page = 0
title = JAVA의 정석 author = 남궁성 page = 0
title = 은노기의 JSP author = 김은옥 page = 789
✅
다른 생성자는 전부 매개변수를 3개 받는 최종 생성자를 호출한다.
→ 중복제거, 유지보수 간편화, 가독성
정리
✅
생성자는 객체가 생성될 때 단 한 번 호출되어, 필드를 초기화하고 객체의 상태를 준비해주는 특별한 메서드
출처: 김영한의 실전 자바 - 기본편
This post is licensed under
CC BY 4.0
by the author.