"객체를 정의한 틀"
public class Example {
static int a = 10; // 클래스 변수
int b = 20; // 인스턴스 변수
public void test() {
int c = 30; // 지역 변수
System.out.println(c);
}
}
public class Main {
public static void main(String[] args) {
Example example = new Example();
System.out.println(Example.a); // 클래스 변수 출력
System.out.println(example.b); // 인스턴스 변수 출력
example.test(); // 지역 변수 출력
}
}
클래스에 생성자를 따로 정의하지 않으면 기본 생성자가 생략된 것으로 간주한다.
class Example {
private int a;
private int b;
Example() {}
Example(int a) {
this.a = a;
}
Example(int a, int b) {
this.a = a;
this.b = b;
}
}
public class Main {
public static void main(String[] args) {
Example ex1 = new Example(); // 기본 생성자
Example ex2 = new Example(1); // 매개변수 있는 생성자
Example ex3 = new Example(1, 5); // 매개변수 있는 생성자
}
}
[생성자 예제 코드]
생성자를 오버로딩해서 생성자를 매개변수에 따라 다르게 정의할 수 있다. 다만 기본 생성자를 정의하지 않고 매개변수가 있는 생성자만 정의를 한다면 기본 생성자를 이용하여 객체를 인스턴스화할때 에러가 발생한다.
class Example {
private int a;
private int b;
private String c;
Example() {
this.c = "example";
}
Example(int a) {
this(); // 매개변수가 있는 생성자에서 기본 생성자 호출
this.a = a;
}
Example(int a, int b) {
this(a); // 매개변수가 여러 개 있는 생성자에서 매개변수가 하나 있는 생성자 호출 가능
this.a = a;
this.b = b;
}
}
public class Main {
public static void main(String[] args) {
Example ex1 = new Example(); // 기본 생성자
Example ex2 = new Example(1); // 매개변수 있는 생성자
Example ex3 = new Example(1, 5); // 매개변수 있는 생성자
}
}
[this와 this() 사용 예]