Java

생성자란? this와 this()의 차이

KJihun 2023. 5. 24. 18:59
728x90
생성자란

인스턴스 생성 시 호출되어 객체를 초기화하는 역할을 수행한다

기본 생성자 : 생성자 선언 시(new();), 괄호안에 아무것도 넣지 않는 생성자

 

 

this와 this()

this와 this()는 이름만 비슷할 뿐, 전혀 다른 역할을 수행한다

  • 우선 this는 인스턴스 변수와 매개변수 이름이 같을 경우, 인스턴스 변수를 호출할 때 사용한다
class Car {
	// 필드에 선언된 변수를 인스턴스 변수라고 함
    String name;
    String color;
    int speed; 
    
    	//괄호안에 있는 변수들을 매개변수라 함
    Car(String name, String color, int speed){	
    
        //this를 통해 인스턴스 변수를 명시적으로 선언
        //매개변수로 전달받은 값을 인스턴스 변수에 대입
        this.name = name;
        this.color = color;
        this.speed = speed;
    }
}

 

  • this()는 인스턴스 자신의 생성자를 호출하는 키워드이다.
    • 객체 내부 생성자 및 메서드에서 해당 객체의 생성자를 호출하기 위해 사용될 수 있다
    • 생성자를 통해 객체의 필드를 초기화할 때 중복되는 코드를 줄여줄 수 있다
    • 반드시 첫 줄에 작성하여야 하며, 다른 문장들보다 앞에 와야한다

this()문을 사용하지 않을 시

class Car {
    String name; 
    String color;
    int speed;
    
    //차의 입력정보에 따라 다르게 저장하여야 할 때,
    //중복된 코드가 많이 발생하게 됨
    public Car(String name){
        this.name = name;
        this.color = "black";
        this.speed = 200;
        
    public Car(String name, String color){	
        this.name = name;
        this.color = color;
        this.speed = 150;
        
    public Car(String name, String color, int speed){	
        this.name = name;
        this.color = color;
        this.speed = speed;
    }
}

this()문 사용 시

class Car {
    String name; 
    String color;
    int speed;
    
    public Car(String name){
    	//자기 자신의 생성자(매개변수가 3개인 것, 16번째 줄)를 호출하여 대입함
        //this()문 위에 어떤 코드도 존재해선 안됨
    	this(name, "black", 200);
    }
    	//똑같이 16번 줄에 있는 생성자를 호출하여 처리함
    public Car(String name, String color){	
    	this(name, color, 150);
    }
    
    public Car(String name, String color, int speed){	
        this.name = name;
        this.color = color;
        this.speed = speed;
    }
}

'Java' 카테고리의 다른 글

추상 클래스  (0) 2023.05.25
super와 super()  (0) 2023.05.24
인스턴스 멤버와 클래스 멤버  (0) 2023.05.24
배열합치기, 컬렉션 합치기  (0) 2023.05.24
아스키 코드(ASCII)  (0) 2023.05.23