[12일차]자바 생성자, this

유태형·2022년 5월 11일
0

코드스테이츠

목록 보기
13/77

오늘의 목표

  1. 생성자
  2. this.와 this()



내용

생성자(Constructor)

생성자는 new키워드가 인스턴스를 만들면 필요한 멤버 변수들을 초기화 하는 역할을 수행하는 특수한 메서드 입니다. 그리고 생서자는 2가지 규칙이 존재합니다.

  1. 리턴타입을 명시하지 않습니다.(void 사용 안함)
  2. 반드시 클래스명과 동일하게 메서드명을 명시합니다.
class 클래스명{
	//생성자
    클래스명(매개변수){
    	//초기화
    }
}

또, 오버로딩(매개변수가 다름)을 통해 여러개의 생성자를 정의할 수도 있습니다.

주의!) 정의한 생성자가 없으면 매개변수가 없는 기본 생서자를 자바가 자동으로 만들어주고, 임의로 지정한 생성자가 한개라도 존재하면 자바가 자동으로 기본생성자를 만들어 주지 않습니다.

package JAVA_OOP_Found;

public class ConstructorExample {
    public static void main(String[] args){
        Constructor constructor1 = new Constructor(); //(1)
        Constructor constructor2 = new Constructor("Hello World"); //(2)
        Constructor constructor3 = new Constructor(5, 10); //(3)
    }
}

class Constructor{
    Constructor(){ //(1)
        System.out.println("1번 생성자");
    }

    Constructor(String str){ //(2)
        System.out.println("2번 생성자");
    }

    Constructor(int a, int b){ //(3)
        System.out.println("3번 생성자");
    }
}

//Console
1번 생성자
2번 생성자
3번 생성자


기본 생성자

기본 생성자는 생성자가 없을 때 자바가 자동으로 추가해주고, 매개변수가 없는 생성자 입니다.

클래스명(){...} //매개변수X, 기본 생서자



매개변수가 있는 생성자

매개 변수가 있는 생성자는 new로 인스턴스를 생성시 메서드 처럼 매개변수를 통해 입력받은 값으로 인스턴스의 멤버 변수를 초기화 할 수 있습니다. 1~2개가 아닌 수천, 수만개의 인스턴스를 만들 때 유용할 것 입니다.

package JAVA_OOP_Found;

public class ConstructorExample2 {
    public static void main(String[] args){
        Car2 c = new Car2("Model x","빨간색",250);
        //순서대로 매개변수에 modelName, color, maxSpeed를 매개변수 인자로 넘겨줍니다.
        System.out.println("제 차는 " + c.getModelName() + "이고, 컬러는 "
        + c.getColor() + "입니다.");
    }
}

class Car2{
    private String modelName;
    private String color;
    private int maxSpeed;

    public Car2(String modelName, String color, int maxSpeed){ //매개변수 3개 가지는 생성자
        this.modelName = modelName; //this.은 자기자신에 대한 포인터
        this.color = color; //자기자신의 변수, 즉 멤버변수를 가리킵니다.
        this.maxSpeed = maxSpeed;
    }

    public String getModelName(){ //String 데이터 타입을 반환
        return modelName; //mdoelName이 가진 값으로 반환합니다.
    }

    public String getColor(){
        return color;
    }
}

//Console
제 차는 Model x이고, 컬러는 빨간색입니다.



this. 와 this()

this()

같은 클래스 안에 생성자들 끼리 서로 서로 호출하는 것이 간으합니다. 이것을 가능하게 만드는 키워드는 this(매개변수)키워드 입니다. 만약 Example클래스의 생성자에서 다른 생성자를 호출하려면 Example()이 아닌 this()로 호출합니다.

이렇게 유용한 this()도 2가지 제약사항이 있습니다.

  1. this()는 반드시 클래스의 생성자 내부에서 사용 되어야 합니다.
  2. this()는 반드시 생성자의 첫 줄에 위치 해야 합니다.
package JAVA_OOP_Found;

public class Example {
    public Example(){ //기본 생성자
        //this(10); 시 Example(int x)호출
        System.out.println("Example의 기본 생성자 호출!");
    };

    public Example(int x){ //매개변수 1개 생성자
        this(); //기본 생성자 호출(매개 변수로 구분)
        System.out.println("Example의 두 번째 생성자 호출!");
    }
}
package JAVA_OOP_Found;

public class Test {
    public static void main(String[] args){
        Example example = new Example();
        Example example2 = new Example(5);
    }
}
//Console
//Example example = new Example();
Example의 기본 생성자 호출!

//Example example2 = new Example(5);
Example의 기본 생성자 호출!
Example의 두 번째 생성자 호출!

int 타입을 받는 생성자 호출 시 가장 먼저 this()메서드를 호출하여 첫 번째 기본 생성자로 이동합니다. 기본 생성자의 작업을 모두 수행한 후 되돌아 와 생성자의 나머지 부분을 수행합니다. 그러므로 example2인스턴스에서 Example의 기본 생성자 호출!이 출력됩니다.



this.

this.this()는 이름이 같지만 하는 역할이 전혀 다릅니다. ConstructorExample2를 다시 보겠습니다.

package JAVA_OOP_Found;

public class ConstructorExample2 {
    public static void main(String[] args){
        Car2 c = new Car2("Model x","빨간색",250);
        //순서대로 매개변수에 modelName, color, maxSpeed를 매개변수 인자로 넘겨줍니다.
        System.out.println("제 차는 " + c.getModelName() + "이고, 컬러는 "
        + c.getColor() + "입니다.");
    }
}

class Car2{
    private String modelName;
    private String color;
    private int maxSpeed;

    public Car2(String modelName, String color, int maxSpeed){ //매개변수 3개 가지는 생성자
        this.modelName = modelName; //this.은 자기자신에 대한 포인터
        this.color = color; //자기자신의 변수, 즉 멤버변수를 가리킵니다.
        this.maxSpeed = maxSpeed;
    }

    public String getModelName(){ //String 데이터 타입을 반환
        return modelName; //mdoelName이 가진 값으로 반환합니다.
    }

    public String getColor(){
        return color;
    }
}

//Console
제 차는 Model x이고, 컬러는 빨간색입니다.

Car2의 생성자는 매개변수를 3개 받습니다. modelName, color, maxSpeed라는 이름으로 존재합니다. 하지만 Car2의 멤버변수로도 modelName, color, maxSpeed 모두 동일한 이름으로 존재중입니다.

이럴 때 생성자는 동일한 이름을 두고 멤버변수인지 매개변수인지 알 수 없는 모호성이 생깁니다. 이를 해결하기 위하여 멤버변수와 매개변수의 이름이 동일할 대는 우선순위 매개변수 > 멤버변수로 동일한 이름이 사용되었다면 매개변수로 간주하게 됩니다. 멤버 변수 = 매개 변수멤버 변수를 초기화 하려고 했지만 동일한 이름이 사용되면 우선순위로 인하여 매개 변수 = 매개 변수로 되어 버려 초기화를 할 수 없게 됩니다.

this는 인스턴스 자기 자신을 가리키는 포인터입니다. this.변수는 자기자신의 변수, 즉 멤버 변수를 가리키게 됩니다. 매개변수와 멤버 변수의 이름이 동일할 때 this.변수 = 변수멤버 변수 = 매개 변수가 될 것입니다. 초기화를 진행할 수 있게 됩니다.




후기

생성자 오버로딩, this., this()는 객체 지향 프로그래밍에서 정말 자주 사용 될것 같고 객체 지향을 이해하는 데 중요할 것 같으니 미리미리 익혀두는게 좋겠습니다.




GitHub

https://github.com/ds02168/CodeStates/tree/main/src/JAVA_OOP_Found

profile
오늘도 내일도 화이팅!

0개의 댓글