티스토리 뷰

Web/JAVA

[JAVA] this()의 의미와 사용

Aaron 2019. 7. 26. 12:58
반응형


#. this()


> this 예약어

  - 생성자나 메서드의 매개변수 이름이 객체 변수의 이름과 같은 경우

  - 객체 변수 이름 앞에 this를 사용해서 구별

  - 멤버 변수와 매개변수 이름을 구분하여 프로그램의 가독성을 높임


> this() 생성자

  - 같은 클래스 내의 Overloading 된 다른 생성자 메서드를 호출할 때 사용 


> 예) 초기화 코드가 중복되어있는 생성자

  - 다양한 변수들을 선택적으로 초기화하기 위해 생성자를 다양하게 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
public class Employee {
        int employeeNo;            
        String name;
        int age;
        int salary;
 
        // 기본 생성자 형태의 생성자
        public Employee() { 
                this.employeeNo = 0;
                this.name = "Annoymity";
                this.age = 0;
                this.salary = 0;
        }
 
        public Employee(int employeeNo, String name) {
                this.employeeNo = employeeNo;
                this.name = name;
        }
 
        public Employee(int employeeNo, String name, int age) {                
                this.employeeNo = employeeNo;
                this.name = name;
                this.age = age;
        }
}
cs


> 예) this()를 사용하여 중복되는 초기화 코드를 최소화한 경우

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Employee {
        int employeeNo;            
        String name;
        int age;
        int salary;
 
        // 기본 생성자 형태의 생성자
        // Employee Aaron = new Employee();
        public Employee() { 
                this(0"Anonymity"00);
        }
 
        // Employee Aaron = new Employee(12123, "박지훈");
        public Employee(int employeeNo, String name) {
                this.employeeNo = employeeNo;
                this.name = name;
        }
 
        // Employee Aaron = new Employee(12123, "박지훈", 25);
        public Employee(int employeeNo, String name, int age) {                
                this(employeeNo, name);
                this.age = age;
        }
}
cs



출처 : SW Expert Academy


반응형
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday