1) 필드의 구분
필드의 구분
필드(field)란 클래스에 포함된 변수(variable)를 의미
클래스 내에서 필드는 선언된 위치에 따라 구분
1. 클래스 변수(static variable)
2. 인스턴스 변수(instance variable)
3. 지역 변수(local variable)
클래스 변수와 인스턴스 변수
클래스 영역에 위치한 변수 중에서 static 키워드를 가지는 변수를 클래스 변수(static variable)라고 함
클래스 영역에 위치한 변수 중 static 키워드를 가지지 않는 변수는 인스턴스 변수(instance variable)라고 함
메소드나 생성자, 초기화 블록 내에 위치한 변수를 지역 변수(local variable)라고 함
클래스 변수는 인스턴스를 생성하지 않고도 바로 사용할 수 있음
이러한 클래스 변수를 공유 변수(shared variable)라고도 함
클래스 변수는 해당 클래스의 모든 인스턴스가 공유해야 하는 값을 유지하기 위해 사용
반면에 인스턴스 변수는 인스턴스마다 가져야 하는 고유한 값을 유지하기 위해 사용
// 클래스에 여러 가지 종류의 변수를 생성하고 참조하는 예제
class Field {
static int classVar = 10; // 클래스 변수 선언
int instanceVar = 20; // 인스턴스 변수 선언
}
public class Member01 {
public static void main(String[] args) {
int var = 30; // 지역 변수 선언
System.out.println(var + "\n"); // 지역 변수 참조
Field myField1 = new Field(); // 인스턴스 생성
Field myField2 = new Field(); // 인스턴스 생성
System.out.println(Field.classVar); // 클래스 변수 참조
System.out.println(myField1.classVar);
System.out.println(myField2.classVar + "\n");
myField1.classVar = 100; // 클래스 변수의 값을 변경
System.out.println(Field.classVar); // 클래스 변수 참조
System.out.println(myField1.classVar);
System.out.println(myField2.classVar + "\n");
System.out.println(myField1.instanceVar); // 인스턴스 변수 참조
System.out.println(myField2.instanceVar + "\n");
myField1.instanceVar = 200; // 인스턴스 변수의 값을 변경
System.out.println(myField1.instanceVar); // 인스턴스 변수 참조
System.out.println(myField2.instanceVar);
}
}
2) 메소드의 구분
메소드의 구분
메소드(method)란 어떠한 작업을 수행하기 위한 명령문의 집합
클래스 내에서 메소드는 static 키워드의 여부에 따라 구분
1. 클래스 메소드(static method)
2. 인스턴스 메소드(instance method)
클래스 메소드와 인스턴스 메소드
static 키워드를 가지는 메소드를 클래스 메소드(static method)라고 함
static 키워드를 가지지 않는 메소드는 인스턴스 메소드(instance method)라고 함
클래스 메소드는 클래스 변수와 마찬가지로 인스턴스를 생성하지 않고도 바로 사용할 수 있음
클래스 메소드는 메소드 내부에서 인스턴스 변수를 사용할 수 없음
메소드 내부에서 인스턴스 변수나 인스턴스 메소드를 사용하지 않는 메소드를 클래스 메소드로 정의하는 것이 일반적
// 클래스의 메소드를 종류별로 생성하고 접근하는 예제
class Method {
int a = 10, b = 20; // 인스턴스 변수
int add() { return a + b; } // 인스턴스 메소드
static int add(int x, int y) { return x + y; } // 클래스 메소드
}
public class Member02 {
public static void main(String[] args) {
System.out.println(Method.add(20, 30)); // 클래스 메소드의 호출
Method myMethod = new Method(); // 인스턴스 생성
System.out.println(myMethod.add()); // 인스턴스 메소드의 호출
}
}
3) 초기화 블록
필드의 초기화
자바에서 필드는 초기화하지 않아도 변수의 타입에 맞는 초깃값으로 자동으로 초기화됨
지역 변수와 마찬가지로 적절한 값으로 초기화한 후에 사용하는 것이 좋음
자바에서는 필드를 초기화하기 위한 방법들
1. 명시적 초기화
2. 생성자를 이용한 초기화
3. 초기화 블록을 이용한 초기화
명시적 초기화는 지역 변수를 초기화하는 방법과 마찬가지로 필드를 선언과 동시에 초기화하는 방법
생성자를 이용한 초기화는 객체의 생성과 동시에 필드를 초기화하는 방법
초기화 블록(initialization block)
초기화 블록이란 클래스 필드의 초기화만을 담당하는 중괄호({})로 둘러싸인 블록
초기화 블록은 생성자보다 먼저 호출되며, static 키워드의 유무에 따라 구분
1. 인스턴스 초기화 블록
2. 클래스 초기화 블록
인스턴스 초기화 블록
인스턴스 초기화 블록은 단순히 중괄호({})만을 사용하여 정의할 수 있음
인스턴스 초기화 블록은 생성자와 마찬가지로 인스턴스가 생성될 때마다 실행
언제나 인스턴스 초기화 블록이 생성자보다 먼저 실행
// 인스턴스 초기화 블록을 이용하여 여러 생성자에서 공통된 부분을 분리하는 예제
class Car {
private String modelName;
private int modelYear;
private String color;
private int maxSpeed;
private int currentSpeed;
{ // 인스턴스 초기화 블록
this.currentSpeed = 0;
}
Car() {}
Car(String modelName, int modelYear, String color, int maxSpeed) {
this.modelName = modelName;
this.modelYear = modelYear;
this.color = color;
this.maxSpeed = maxSpeed;
}
public int getSpeed() {
return currentSpeed;
}
}
public class Member03 {
public static void main(String[] args) {
Car myCar = new Car(); // 인스턴스 생성
System.out.println(myCar.getSpeed()); // 인스턴스 메소드의 호출
}
}
클래스 초기화 블록
클래스 초기화 블록은 인스턴스 초기화 블록에 static 키워드를 추가하여 정의할 수 있음
클래스 초기화 블록은 클래스가 처음으로 메모리에 로딩될 때 단 한 번만 실행
클래스 초기화 블록은 생성자나 인스턴스 초기화 블록으로는 수행할 수 없는 클래스 변수의 초기화를 수행할 때 사용
// 클래스 초기화 블록을 이용하여 클래스 변수를 초기화하는 예제
class InitBlock {
static int classVar; // 클래스 변수
int instanceVar; // 인스턴스 변수
static { // 클래스 초기화 블록을 이용한 초기화
classVar = 10;
}
}
public class Member04 {
public static void main(String[] args) {
System.out.println(InitBlock.classVar); // 클래스 변수에 접근
}
}
필드의 초기화 순서
자바에서 필드는 다음과 같은 순서로 초기화
1. 클래스 변수 : 기본값 → 명시적 초기화 → 클래스 초기화 블록
2. 인스턴스 변수 : 기본값 → 명시적 초기화 → 인스턴스 초기화 블록 → 생성자
// 클래스 변수와 인스턴스 변수가 초기화되는 순서를 보여주는 예제
class InitBlock {
static int classVar = 10; // 클래스 변수의 명시적 초기화
int instanceVar = 10; // 인스턴스 변수의 명시적 초기화
static { classVar = 20; } // 클래스 초기화 블록을 이용한 초기화
{ instanceVar = 20; } // 인스턴스 초기화 블록을 이용한 초기화
InitBlock() { instanceVar = 30; } // 생성자를 이용한 초기화
}
public class Member05 {
public static void main(String[] args) {
System.out.println(InitBlock.classVar);
InitBlock myInit = new InitBlock();
System.out.println(myInit.instanceVar);
}
}
출처 : www.tcpschool.com/
댓글