Java 선언위치에 따른 변수의 종류
선언위치에 따른 변수의 종류
변수의 종류 | 선언위치 | 생성시기 |
---|---|---|
클래스 변수 | 클래스영역 | 클래스가 메모리에 올라갈 때 (같은 클래스끼리 공유) |
인스턴스 변수 | 클래스영역 | 인스턴스가 생성되었을 때 |
지역 변수 | 클래스 영역 이외의 영역 (매서드, 생성자, 초기화 블럭 내부) | 변수 선언문이 수행되었을 때 |
class Variables
{
int iv; // 인스턴스 변수
static int cv; // 클래스 변수(static변수, 공유변수)
void method()
{
int lv = 0; // 지역변수
}
}
클래스 변수와 인스턴스 변수
- 인스턴스 변수 : 카드의 숫자 무늬(각 카드마다 다른 값을 가짐)
- 클래스 변수 : 폭, 너비(모든 카드가 같은 값을 가짐)
- 모든 인스턴스가 공통적으로 가지는 속성을 클래스 변수로 둔다.
class Card
{
String kind;
int number;
static int width = 100;
static int height = 250;
}
Card c = new Card();
c.kind = "HEART";
c.number = 7;
c.width = 200; // 보통 이렇게 잘 쓰이지 않음
c.height = 300; // 보통 이렇게 잘 쓰이지 않음
Card.width = 200;
Card.height = 300;
변수의 초기화
- 지역변수(lv)는 수동 초기화 해야한다.(사용전 꼭!!!)
- 멤버 변수(iv, cv 등)의 경우에는 자동으로 초기화가 된다.(초기화 대상이 많을 수 있기 때문)
class InitTest{
int x;
int y = x;
void method1(){
int i; // 지역변수
int j = i; // error : 지역 변수를 초기화하지 않고 사용
}
}
멤버 변수의 초기화
- 명시적 초기화 :
=
대입 연산자를 통해 선언
class Car{
int door = 4; // 기본형(primitive type) 변수의 초기화
Engine e = new Engine(); // 참조형(reference type) 변수의 초기화
// 참조형 변수를 초기화하기 위해서 객체를 생성해서 넣어주어야 한다.
}
- 초기화 블럭(복잡한 초기화에 사용)
- 인스턴스 초기화 블럭 :
{ }
- 클래스 초기화 블럭 :
static { }
class StaticBlockTest{
static int[] arr = new int[10]; // 명시적 초기화
static { // 클래스 초기화 블럭 - 배열 arr을 난수로 채운다.
for(int i=0; i<arr.length; i++){
arr[i] = (int)(Math.random()*10)+1;
}
}
}
- 생성자(iv 초기화, 복잡한 초기화에 사용)
Car(String color, String gearType, int door){ // 매개변수 있는 생성자
this.color = color;
this.gearType = gearType;
this.door = door;
}
클래스 변수 초기화 시점
- 클래스가 처음 로딩될 때 단 한 번(클래스가 메모리에 올라갈 때)
인스턴스 변수 초기화 시점
- 인스턴스가 생성될 때 마다
class InitTest{
static int cv = 1; // 명시적 초기화
int iv = 1; // 명시적 초기화
static { cv = 2; } // 클래스 초기화 블럭
{ iv = 2; } // 인스턴스 초기화 블럭
InitTest(){ // 생성자
iv = 3;
}
}
Author And Source
이 문제에 관하여(Java 선언위치에 따른 변수의 종류), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@nathan29849/Java-선언위치에-따른-변수의-종류저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)