본문 바로가기
프로그래밍/Java

[JAVA 이론] this / this()

by purplebulb 2019. 1. 20.
반응형


1. this


(1) 인스턴스 멤버 (instance member)


① 정의 : 객체(인스턴스)를 생성한 후 사용할 수 있는 필드와 메소드

② 특징 : 객체에 소속된 멤버로 외부 클래스에서 사용하기 위해서는 객체(인스턴스)를 생성하고 접근해야 함


③ 예시


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Car {
 
    // 멤버 필드
    int gas;
 
    // 멤버 메소드
    void setSpeed(int Speed) {
        if (speed < 0) {
            this.speed = 0;
            return;
        }else {
            this.speed = speed;                       
        }     
    }
 
}



1
2
3
4
5
6
7
8
public static void main(String[] args) {
        
    Car car = new Car();
        
    car.gas = 10;
    car.setSpeed(60);
        
}





(2) 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
25
26
27
28
29
30
public class PeopleInfo {
 
    // 1. 필드
    String name;
    int age;
    
    // 2. 생성자
    PeopleInfo(String name){
        this.name = name;
    }
    
    // 3. 메소드
    void setAge(int age){
        this.age = age;
    }
    
    
    void ageInfo() {
        for (int i = 10; i <= 30; i+=10) {
            this.setAge(i);
            System.out.println(this.name + "의 나이는" + this.age + "입니다.");
        }
    }
 
    
    public static void main(String[] args) {
        PeopleInfo peopleInfo = new PeopleInfo("홍길동");
        peopleInfo.ageInfo();
    }
}




* [결과]




2. this()


(1) 내용

- 생성자에서 다른 생성자를 호출할 때 사용

한 생성자에 공통적으로 실행할 코드를 작성하고 나머지 생성자는 초기화 내용을 가진 생성자를 호출


(2) 목적 : 생성자간의 중복된 코드가 많아 코드를 중복 기재하는 문제를 개선하기 위해 사용

 

(3) 사용 조건

- 생성자의 첫 줄에서만 사용할 수 있음

- 매개값은 호출되는 생성자의 매개 변수 타입에 맞게 제공해야 함



* [예시]


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
public class PeopleInfo {
 
    // 1. 필드
    String name;
    String address;
    int age;
 
    
    // 2. 생성자
    PeopleInfo(){
    }
    
    PeopleInfo(String name){
        this(name, "서울"32);
    }
    
    PeopleInfo(String name, String address){
        this(name, address, 23);
    }
    
  // 다른 생성자에서 호출하는 공통 실행 코드
    PeopleInfo(String name, String address, int age){
        this.name = name;
        this.address = address;
        this.age = age;
    }
    
}




댓글