Constructors and Initialization
Constructor #
- A constructor is a type of method (but different from a method) that is always called and executed first when an instance is created using the
newoperator. - A constructor's role is to initialize
instance variables(such as field values).
How to Declare a Constructor #
public 클래스(매개변수){
...
}
- The
classpart must be written identically to the name of the class defining the constructor. - Parameters are not necessarily required.
- When declaring a constructor, you can simply write
public.
Types and Usage of Constructors #
A constructor must be called when creating an instance. But how has it been called so far without us defining one? The reason is that when you define a class, if you omit the constructor, the compiler automatically generates a default constructor. A Default constructor means "public ClassName(){}".
public class ConstructorEx01{
// public ConstructorEx01(){} // Default Constructor 자동 생성
public static void main(String[] args){
ConstructorEx01 ce = new ConstructorEx01(); // 인스턴스 생성 및 생성자 호출
}
}
As shown above, a constructor is called when creating an instance. If the constructor is omitted, the commented-out part is automatically generated. Now, let's look at how to define a default constructor directly.
public class ConstructorEx01{
public ConstructorEx(){
System.out.println("생성자 호출 성공");
public static void main(String[] args){
ConstructorEx01 ce = new ConstructorEx01(); // 인스턴스 생성 및 생성자 호출
}
}
}
Compared to the first example, the difference is that "생성자 호출 성공" (Constructor call successful) is printed at the beginning.
We mentioned that constructors can have parameters within parentheses when declared, so let's look at an example of that.
public class ConstructorEx02{
public ConstructorEx02(String a){
// a = 사용자 거의
System.out.println(a + "생성자 호출 성공");
}
public static void main(String[] args){
ConstructorEx02 ce = new ConstructorEx02("사용자 정의") // 매개 변수를 갖는 생성자. 매개변수를 할당하지 않으면 컴파일 에러가 발생한다.
}
}
- The reason a compile error occurs when parameters are not assigned is that if you just call it, a Default constructor would be created, but since a constructor already exists, it is not created.
public class ConstructorEx03 {
public ConstructorEx03(){
System.out.println("생성자 호출 성공");
}
public ConstructorEx03(String a){ // a = 사용자 정의
System.out.println(a + " 생성자 호출 성공");
}
public static void main(String[] args) {
ConstructorEx03 ce = new ConstructorEx03("사용자 정의"); // 매개변수를 갖는 생성자 호출
ConstructorEx03 ce2 = new ConstructorEx03(); // 기본 생성자 호출
}
}
- By using overloading, the error that occurred when no arguments were passed to the parameters was resolved.
The role of a constructor is to initialize instances. Let's find out what that means.
class CalculatorEx {
// 필드변수 선언
int a;
int b;
public CalculatorEx() { // 기본 생성자
// 필드변수 초기화
a = 10;
b = 20;
}
public CalculatorEx(int num1, int num2) { // 생성자 오버로딩
// 매개값 이용 필드변수 초기화
a = num1;
b = num2;
}
public void sum() { // 메소드
System.out.println("합계 : " + (a + b));
}
}
public class ConstructorEx04 {
public static void main(String[] args) {
CalculatorEx cc = new CalculatorEx();
cc.sum(); // 결과 : 30
CalculatorEx cc2 = new CalculatorEx(0, 10);
cc2.sum(); // 결과 : 10
}
}
A separate class was defined, and field variables (int a, int b) were declared. A default constructor and a constructor with parameters were defined, and code to calculate the sum was added in a method. In the main method, the constructor was called while creating an instance, and the field variables were initialized by the called constructor. Then, the method is called using the instance to print the values.
Characteristics of Constructors (Differences from Methods) #
- As explained earlier, a constructor must be
defined with the same name as the class. - Only access modifiers can precede a constructor. (Methods can have modifiers like
static.) - Since there is no return value,
voidor a data type cannot be written. (Methods must havevoidor a data type.)