○ RAM 메모리 공간
- static이라는 특성은 JAVA 언어 자체의 특성이 아니라 RAM의 메모리 공간의 특성
- RAM 메모리 공간은 static, heap, stack으로 구분됨
① static
- continue
- 프로그램이 시작될 때 할당되고, 프로그램이 종료될 때 소멸
- 전역변수, 정적변수가 저장되는 공간
② heap
- new
- new연산자를 이용해 만들어진 객체(인스턴스)가 저장되는 공간 (참고 : new 연산자)
③ stack
- reset
- 함수가 호출될 때 할당되고, 호출이 종료될 때 소멸
- 지역변수, 매개변수가 저장되는 공간
○ static
- 메모리에 생성도 1번, 소멸도 1번 됨 (continue)
- new연산자를 이용해서 별도의 객체 생성 없이 사용가능 (클래스명으로 직접 접근 가능)
형식) 클래스명.변수 / 클래스명.함수()
System.out.println(Math.PI);
System.out.println(Math.abs(-3));
//Math ma=new Math();
//일반적으로 메소드나 변수를 사용할 때는 new연산자를 이용해 메모리를 먼저 할당해야 하지만
//static(정적) 변수, 메소드는 바로 사용가능
- Sawon클래스를 생성하고 실습
public class Sawon {
//멤버변수 field
String sabun; //사원번호
String name; //이름
int pay; //급여
//생성자함수 constructor
public Sawon() {}
public Sawon(String sabun, String name, int pay) {
this.sabun = sabun;
this.name = name;
this.pay = pay;
}
//static 변수 (보통 대문자로 e.g. Math.PI)
static String COMPANY="(주)솔데스크";
static int SUDANG=10;
static double TAX=0.03;
//static 함수
static void line() {
System.out.println("----------------------------------");
}
}//class end
① static 변수와 static 함수는 클래스명으로 직접 접근한다
System.out.println(Sawon.COMPANY); //(주)솔데스크
System.out.println(Sawon.SUDANG); //10
System.out.println(Sawon.TAX); //0.03
Sawon.line(); //----------------------------------
② static의 특징을 적용하지 않은 경우(비추천)
Sawon one=new Sawon("1001", "개나리", 100);
//나의 세금
double myTax=one.pay*one.TAX;
//나의 총 지급액=급여-세금+수당
int total=(int)(one.pay-myTax+one.SUDANG);
System.out.println("회사: " + one.COMPANY);
System.out.println("사번: " + one.sabun);
System.out.println("이름: " + one.name);
System.out.println("총지급액: " + total);
one.line();
③ static의 특징을 적용한 경우(추천)
- static변수와 static함수는 이미 static메모리에 값이 올라와 있기 때문에
별도의 객체 생성을 하지 않고도 바로 접근할 수 있다
Sawon two=new Sawon("1002", "진달래", 200);
double myTax=two.pay*Sawon.TAX;
int total=(int)(two.pay-myTax+Sawon.SUDANG);
System.out.println("회사: " + Sawon.COMPANY);
System.out.println("사번: " + two.sabun);
System.out.println("이름: " + two.name);
System.out.println("총지급액: " + total);
Sawon.line();
④ static변수의 연산(continue)
- static메모리의 특징은 생성도 1번, 소멸도 1번
- 주소를 공유한다
Sawon kim=new Sawon("1003", "무궁화", 300);
Sawon lee=new Sawon("1004", "봉선화", 400);
System.out.println(kim.SUDANG); //10
System.out.println(lee.SUDANG); //10
kim.SUDANG=kim.SUDANG+1;
System.out.println(kim.SUDANG); //11 (10+1)
lee.SUDANG=lee.SUDANG+1;
System.out.println(lee.SUDANG); //12 (11+1)
//kim.SUDANG이나 lee.SUDANG이나 같은 Sawon.SUDANG
//하나를 계속 재활용(continue > reset하지 않는다!)
Sawon.SUDANG=Sawon.SUDANG+1;
System.out.println(Sawon.SUDANG); //13 (12+1) 추천
- static하면 2가지 기억할 것 : 클래스명으로 직접 접근 가능, continue(연산될 때)
'Backend > JAVA_Basic' 카테고리의 다른 글
17. JAVA, getter와 setter함수 (0) | 2022.06.02 |
---|---|
16. JAVA, final (final클래스, final메소드) & 연습문제 (0) | 2022.06.02 |
14. JAVA, 문자열 관련 클래스(String, StringBuffer, StringBuilder, StringTokenizer) (0) | 2022.06.02 |
13. JAVA, String 클래스 관련 메소드(substring, length, equals ...) & 연습문제 (0) | 2022.06.01 |
12. JAVA, 생성자 함수(Constructor) (0) | 2022.05.31 |
댓글