![[자바 #16] 생성자 선언과 호출](https://image.inblog.dev?url=https%3A%2F%2Finblog.ai%2Fapi%2Fog-custom%3Ftitle%3D%255B%25EC%259E%2590%25EB%25B0%2594%2B%252316%255D%2B%25EC%2583%259D%25EC%2584%25B1%25EC%259E%2590%2B%25EC%2584%25A0%25EC%2596%25B8%25EA%25B3%25BC%2B%25ED%2598%25B8%25EC%25B6%259C%26tag%3DTemplate%2B1%26description%3D%26template%3D3%26backgroundImage%3Dhttps%253A%252F%252Fsource.inblog.dev%252Fog_image%252Fdefault.png%26bgStartColor%3D%25233f0707%26bgEndColor%3D%25233f0707%26textColor%3D%2523000000%26tagColor%3D%2523000000%26descriptionColor%3D%2523000000%26logoUrl%3D%26blogTitle%3DGyeongwon%2527s%2Bblog&w=2048&q=75)
new 연산자는 객체를 생성한 후 연이어 생성자를 호출해서 객체를 초기화하는 역할을 한다. 객체 초기화란 필드 초기화를 하거나 메소드를 호출해서 객체를 사용할 준비를 하는 것을 말한다.
클래스 변수 = new 클래스()
클래스()에서 생성자를 호출한다.
1. 기본 생성자
클래스의 생성자선언이 없으면 컴파일러는 다음과 같은 기본 생성자를 바이트코드 파일에 자동으로 추가시킨다.
[public] 클래스 () {}
2. 생성자 선언
public class Car {
// 생성자선언
Car(String model, String color, int maxSpeed) {
}
}
public class CarExample {
public static void main(String[] args) {
Car myCar = new Car("그랜저", "검정", 250);
// Car myCar = new Car(); // 기본 생성자 호출 못함
}
}
3. 필드 초기화
객체마다 동일한 값을 갖고 있다면 필드 선언 시 초기값을 대입하는 것이 좋고, 객체마다 다른 값을 가져야 한다면 생성자에세 필드를 초기화하는 것이 좋다.
예를 들어 Korean 클래스를 선언한다고 가정해 보자. 한국인이므로 nation(국가)은 대한민국으로 동일한 값을 가지지만, name(이름)과 ssn(주민등록번호)은 한국인마다 다르므로 생성자에서 초기화하는 것이 좋다.
public class Korean {
// 필드 선언
String nation = "대한민국";
String name;
String ssn;
// 생성자 선언
public Korean(String name, String ssn) {
this.name = naeme;
this.ssn = ssn;
}
}
public class KoreanExample {
public static void main(String[] args) {
// Korean 객체 생성
Korean k1 = new Korean("박자바", "011225-1234567");
// Korean 객체 데이터 읽기
System.out.println("k1.nation: " + k1.nation);
System.out.println(k1.name);
System.out.println(k1.ssn);
// 또 다른 Korean 객체 생성
Korean k2 = new Korean("김자바", "930525-0654321");
// 또 다른 Korean 객체 데이터 읽기
System.out.println(k2.nation);
System.out.println(k2.name);
System.out.println(k2.ssn);
this는 현재 객체를 말하며, this.name은 현재 객체의 데이터(필드)로서의 name을 뜻한다.
4. 생성자 오버로딩
매개값으로 객체의 필드를 다양하게 초기화 하기위해 생성자 오버로딩이 필요하다.
생성자 오버로딩이란 매개변수를 달리하는 생성자를 여러 개 선언하나는 것을 말한다.
public class Car {
//필드 선언
String company = "현대자동차";
String model;
String color;
int maxSpeed;
//생성자 선언 (4개)
Car() {}
Car(String model) {
this.model = model;
}
Car(String model, String color) {
this.model = model;
this.color = color;
}
Car(String model, String color, int maxSpeed) {
this.model = model;
this.color = color;
this.maxSpeed = maxSpeed;
}
}
public class CarExample {
public static void main(String[] args) {
Car car1 = new Car(); // 생성자 1 호출
System.out.println(car1.company);
Car car4 = new Car("택시", "검정", 200);
System.out.println(car4.company);
System.out.println(car4.model);
System.out.println(car4.color);
System.out.println(car4.maxSpeed);
Share article