[Java] 객체지향 (4) 생성자와 this 키워드

lkc9898·2022년 5월 16일

Java

목록 보기
14/25
post-thumbnail

생성자(Constructor)란

생성자는 말 그대로 객체를 생성하는 역할을 하는 클래스의 구성 요소로서 인스턴스가 생성될 때 호출되는 인스턴스 초기화 메서드이다. 하지만 메서드와는 다른점이 있는데 첫 번째는 생성자의 이름이 반드시 클래스의 이름과 같아야 한다는 점, 두 번째는 생성자는 리턴 타입이 없다는 점이다.

생성자 선언

클래스명(매개변수) { // 매개변수가 없을 수도 있다.
	...
}

코드 예시

public class Constructor {
	public Constructor() { ... } // 생성자
}
  • 생성자의 이름은 반드시 클래스 이름과 동일하게 작성한다.
public class Constructor {
	public Constructor() { ... }
    // 매개변수가 없는 생성자
    
    public Constructor(int a, String b) { ...}
    // 2개의 매개변수를 가진 생성자
  • 생성자는 여러개 작성할 수 있다.
Constructor ex1 = new Constructor(5, "abc");
// 생성자 Constructor(int a, String b) 호출

Constructor ex2 = new Constructor(); 
// 생성자 Constructor() 호출
  • 생성자는 new키워드를 통해 객체를 생성할 때 한번만 호출된다.
public void Constructor() { ... }
// 오류
  • 생성자는 어떤 값도 리턴하지 않기 때문에 리턴 타입을 지정할 수 없다.

thisthis()

자바에서 'this'와 'this()'의 차이점은 'this' 키워드는 인스턴스 자신을 가르키고, 'this()' 키워드는 생성자를 뜻한다.

'this' 키워드

class car {
	String color;
    String gearType;
    int door;
    
    Car(String color, String gearType, int door) {
    	this.color = color;
        this.gearType = gearType;
        this.door = door;
    }
}
  • 'this'는 생성자의 매개변수로 선언된 변수의 이름이 인스턴스 변수와 같을 때 인스턴스 변수와 지역변수를 구분하기 위해 사용한다.

  • 생성자 안에서의 this.color는 인스턴스 변수, color는 매개변수로 정의된 지역변수이다.

  • static 메서드에서는 this를 사용할 수 없다.

'this()' 키워드

class Car {
	String color;
    String gearType;
    int door;
    
    Car() {
    	this("white", "auto", 4);
        // Car(String color, String gearType, int door)
    }
    
    Car(String color) {
    	this(color, "auto", 4);
    }
    
    Car(String color, String gearType, int door) {
    	this.color = color;
        this.gearType = gearType;
        this.door = door;
    }
}
  • this()는 같은 클래스의 다른 생성자를 호출할 때 사용한다.

  • Car() 생성자와 Car(String color) 생성자는 this()를 통해 모두 Car(String color, String gearType, int door) 생성자를 호출하고 있다.

0개의 댓글