티스토리 뷰
2. 생성자
1. 생성자 개요
- Constructor는 클래스로부터 객체를 생성할 때 호출되며, 객체의 멤버 변수를 초기화하는 메서드다.
- 클래스와 같은 이름을 가진 메서드다.
- 일반 메서드와 달리 반환형 (Return Type)이 없으며 void도 허용되지 않는다.
- 생성자는 이름은 같지만 매개변수를 달리하여 여러 개를 중복정의 (Overloading)할 수 있다.
- 생성자는 객체를 생성할 때 new 생성자() 구문으로 호출된다.
- 명시적으로 작성하지 않을 경우 기본 생성자가 제공된다.
기본 생성자 (Default Constructor)
-
클래스에 생성자가 하나도 정의되지 않은 경우, 컴파일러에 의해 자동으로 생성되는 생성자
-
매개변수가 없는 생성자
class Employee {
// 생성자를 가지고 있지 않은 클래스 => 기본 생성자 자동 추가
String name;
int number;
int age;
String title;
String dept;
String grade;
}
public class DefaultConstructorTest {
public static void main(String[] args) {
Employee kim = new Employee(); // 기본 생성자로 초기화됨
System.out.println("이름 : " + kim.name);
System.out.println("사번 : " + kim.number);
System.out.println("나이 : " + kim.age);
System.out.println("직함 : " + kim.title);
System.out.println("근무 부서 : " + kim.dept);
System.out.println("등급 : " + kim.grade);
// 이름 : null
// 사번 : 0
// 나이 : 0
// 직함 : null
// 근무 부서 : null
// 등급 : null
}
}
Constructor 생성
- 생성자 자동 생성 : Alt + Shift + S => Generate Constructor using Fields
class Employee {
String name;
int number;
int age;
String title;
String dept;
String grade;
// 사원의 이름과 나이를 초기화하는 생성자
// public Employee(String n, int a) {
// name = n;
// age = a;
// }
// Alt + Shift + S => Generate Constructor using Fields
public Employee(String name, int number, int age, String title, String dept, String grade) {
super();
this.name = name;
this.number = number;
this.age = age;
this.title = title;
this.dept = dept;
this.grade = grade;
}
}
public class EmployeeTest {
public static void main(String[] args) {
Employee sung = new Employee("성나정", 25); // 매개변수 두 개로 생성자 호출, 객체 생성, 초기화
System.out.print(sung.name + " 사원의 나이 : " + sung.age);
// 성나정 사원의 나이 : 25
}
}
2. this
의 의미와 사용법
- 생성자나 메서드의 매개변수 이름이 객체 변수의 이름과 같다면, 객체 변수 이름 앞에
this
를 사용해서 구별한다. - 일반 메소드에서도
this
사용
class Employee {
String name;
int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
출처 - swexpertacademy.com/
'Java > Java Basic' 카테고리의 다른 글
[Java] 2-04 - 매개변수 - 값 복사, 주소 복사, Call by value, Call by reference (0) | 2021.01.09 |
---|---|
[Java] 2-04 - 메서드 Overloading, this() 생성자 (0) | 2021.01.09 |
[Java] 2-03 - 자바 Modifier : static, final, abstract, 인스턴스 변수, 클래스 변수, 상수, 추상 메소드와 추상 클래스 (0) | 2021.01.09 |
[Java] 2-02 - 클래스의 구조 - 접근제한자와 정보은닉, 메서드 자동 생성, Getter(), Setter(), toString() (0) | 2021.01.09 |
[Java] 2-01 - 객체지향 핵심 개념 (0) | 2021.01.09 |
댓글