✍ 생성자의 핵심 개념과 기본 문법을 이해하고 사용할 수 있다.
✍ 생성자가 메서드와 구분되는 두 가지 차이를 이해하고 설명할 수 있다.
✍ 메서드 오버로딩이 생성자에서 어떻게 구현될 수 있는 지 확인하고 이해할 수 있다.
✍ this 와 this() 의 차이에 대해 설명할 수 있다.
생성자 : 인스턴스가 생성될 때 호출되는 인스턴스 초기화 메서드
🟡 생성자의 이름은 반드시 클래스의 이름과 같아야 함
🟡 생성자는 리턴 타입이 없음
생성자 예제
public class ConstructorExample {
public static void main(String[] args) {
Constructor constructor1 = new Constructor();
Constructor constructor2 = new Constructor("Hello World!");
Constructor constructor3 = new Constructor(5,10);
}
}
class Constructor{
Constructor() {
System.out.println("1번 생성자");
}
Constructor(String str) {
System.out.println("2번 생성자");
}
Constructor(int a, int b) {
System.out.println("3번 생성자");
}
}
결과 :
1번 생성자
2번 생성자
3번 생성자
매개변수가 없는 생성자와 문자열을 매개변수로 받는 생성자 매개변수가 정수가 2개인 생성자는 각기 다른 생성자를 생성한다. -> 메서드 오버로딩이 생성자에도 적용됨
🍄 this() : 자신이 속한 클래스에서 다른 생성자를 호출할 때 사용
🚫 this() 사용 주의사항 🚫
🔴 생성자 내에서만 사용 가능
🔴 반드시 첫 줄에 위치해야함
this() 예제
public class Test {
public static void main(String[] args) {
Example example = new Example();
Example example2 = new Example(5);
Example example3 = new Example("hello");
}
}
class Example{
public Example() {
System.out.println("Example의 기본 생성자 호출!");
}
public Example(int x) {
System.out.println("Example의 두 번째 생성자 호출!");
}
public Example(String str) {
this(5);
System.out.println("Example의 세 번째 생성자 호출!");
}
}
결과
Example의 기본 생성자 호출!
Example의 두 번째 생성자 호출!
Example의 두 번째 생성자 호출!
Example의 세 번째 생성자 호출!
this()를 사용해서 정수형을 인자로 받은 두 번째 생성자를 세 번째 생성자에서 호출했다.
🍄 this : 인스턴스 변수와 매개변수의 이름이 겹칠 때 둘을 구분 짓기 위해 사용한다. this는 인스턴스 자신을 가리키며 this를 통해서 인스턴스 자신의 변수에 접근한다.
this 예제
public class ConstructorExample {
public static void main(String[] args) {
Car car = new Car("Model X", "빨간색", 250);
System.out.println("제 차는 " + car.getModelName() + "이고, 컬러는 " + car.getColor() + "입니다.");
}
}
class Car {
private String modelName;
private String color;
private int maxSpeed;
public Car(String modelName, String color, int maxSpeed) {
this.modelName = modelName;
this.color = color;
this.maxSpeed = maxSpeed;
}
public String getModelName() {
return modelName;
}
public String getColor() {
return color;
}
}
결과
제 차는 Model X이고, 컬러는 빨간색입니다.
코드 설명 : Car라는 생성자를 만들어 this.인스턴스 변수명으로 매개변수와 인스턴스 변수명을 구분지어 작성했다.
클래스 내에 선언되는 클래스로 외부클래스의 멤버들에 쉽게 접근할 수 있고, 코드의 복잡성을 줄일 수 있다. 또한 캡슐화를 달성할 수 있다.
🍄 인스턴스 내부클래스 : 외부 클래스의 모든 멤버에 접근이 가능하다.
🍄 정적 내부클래스 : 외부클래스의 존재와 관계없이 정적 변수를 사용 할 수 있다.(하지만 인스턴스 변수와 메서드는 사용 불가능하다.)
🍄 지역 내부클래스 : 클래스 멤버가 아닌 메서드 안에서 정의되는 클래스로 지역 변수와 같이 메서드 안에서만 사용 가능하다.