생성자2 변수의 초기화 클래스의 멤버 변수의 초기화 방법에는 3가지 종류가 있다. 명시적 초기화(Explicit initialization) 생성자(Constructor) 초기화 블럭(Initialization block) 인스턴스 초기화 블럭 클래스 초기화 블럭 1. 명시적 초기화(Explicit initialization) 변수를 선언과 동시에 초기화 하는 방법 class Car { int door = 4; Engine e = new Engine(); } 2. 생성자(Constructor) class Car { int door; Engine e; Car() { door = 4; e = new Engine(); } } 3. 초기화 블럭(Initialization block) 클래스 초기화 블럭: 클래스변수의 복잡한 초기화에 .. 2022. 1. 20. [소소한 정보] this와 this() 생성자에서 다른 생성자를 호출할 수 있다. 단 2가지 조건이 있다. 다른 생성자를 호출할 때 생성자의 이름으로 클래스 이름이 아닌 this를 사용한다. 반드시 생성자의 첫 줄에서만 다른 생성자를 호출할 수 있다. class Test { int temp1; int temp2; Test() { this(0); temp2 = 0; } Test(int temp1) { this.temp1 = temp1; } } Test()에서 this(0)으로 다른 생성자를 호출했다. //Case 1 Test() { Test(0); //this가 아닌 클래스명을 사용해서 생성자 호출 this.temp2 = 0; } //Case 2 Test() { this.temp2 = 0; this(0); //첫 줄에서 다른 생성자를 호출하지 .. 2022. 1. 20. 이전 1 다음