필드는 클래스에 포함된 변수를 의미한다.
자바에서 변수의 종류는
클래스변수, 인스턴스 변수, 지역변수가 있고,
필드에서 다루는 변수는 클래스변수와 인스턴스변수가 있고 이 둘은 static으로 구분한다.
class Variable {
static int classVariable; // 클래스 변수(static 변수 또는 공유변수)
int instanceVariable; // 인스턴스 변수
void variableMethod() {
int localVariable; // 지역변수, 메서드 내에서만 사용 가능
}
}
클래스변수는 공통된 저장공간을 공유한다.
한 클래스로부터 생성된 모든 인스턴스들이 특정값을 공유해야하는 경우 static키워드를 통해 선언한다.
클래스명.클래스변수로 사용가능하다.
class Variable{
static int classVariable = 10;
public static void main(String args[]){
System.out.println(Variable.classVariable); //10출력
}
}
인스턴스(클래스를 통해 생성된 객체)가 가지는 속성에 대한 변수이다.
new 생성자(); 를 통해 생성되고 인스턴스명.인스턴스변수명 으로 사용가능하다.
class InstanceVariable{
static int classVariable = 5;
int instanceVariable = 10;
public static void main(String args[]){
InstanceVariable iv = new InstanceVariable();
System.out.println(Variable.classVariable); //5출력
System.out.println(iv.instanceVariable); //10출력
}
}
지역 변수는 클래스 변수, 인스턴스 변수랑 구분되게 메서드 내에 선언되며 메서드 안에서만 사용이 가능하다.
또한, 멤버 변수와는 다르게 지역 변수는 스택 메모리에 저장되어 메서드가 종료되는 동시에 소멸된다.
class localVariable{
static int classVariable = 5;
int instanceVariable = 10;
public static void main(String args[]){
InstanceVariable iv = new InstanceVariable();
System.out.println(Variable.classVariable); //5출력
System.out.println(iv.instanceVariable); //10출력
//System.out.println(instanceVariable); //에러
}
public static void printLocal(){
int localVariable = 20;
System.out.println(instanceVariable); //20출력
}
}
static은 정적이라는 의미이며 자바에서는 static을 붙여서 static변수, static메소드를 정의 할 수있다.
static이 붙으면,
메모리에 고정으로 할당되고,객체를 생성하지않고도 변수나 메소드를 사용할 수 있다.
그래서 static키워드는 인스턴스들이 공통적으로 값을 유지해야할때 사용한다.
참고 출처 : https://ittrue.tistory.com/118