20.03 ~ 20.08 국비교육/JAVA

클래스 JVM 메모리 운영, Static variable과 Method

찹키리 2020. 3. 22. 15:05

<메모리운영>


1. 지역 변수(함수 내)
2. 멤버 변수(전역변수, 함수 외)
3. 클래스 변수(static 내부)

 

 

실행 소스  
code segment  

 

data segment

상수 - 기본값 O, 기본값 X

문자열

static - 변수, 메소드

-로드시 바로 메모리를 할당받음(인스턴스 생성 불필요) -> 진행속도가 빠르다.

-1회만 생성, 모든 인스턴스가 같이 사용 -> 공유변수

-클래스 변수(를 직접 호출)

heap

객체영역(인스턴스를 할당하는 메모리 영역)

-멤버변수

-멤버 메소드

 

데이터 저장

-멤버변수, 지속성

-garbage collection(자동 메모리 수거)

stack

메소드 실행영역

------------------------------------

method(); 실행 뒤 바로 사라짐

-지역변수, 메소드와 함께 실행되다 사라진다.

-Last Input First Out(<-> FIFO)

-메모리 자동반환



*garbage collection(gc): "사용되지 않는" 힙(heap) 영역의 메모리를 자동으로 수거하는 기능
-> a = null; ---> gc의 대상이 된다. 가상머신이 알아서 수거해 준다.

 

*클래스

-변수

-메소드

-main ---> static 영역

--main 안의 인스턴스 ---> heap 영역

 

*stack에서 메소드 실행 -> heap에 데이터 저장 -> static의 클래스 변수 초기화

 

 

<예제>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 
class MethodTest {
 
    String name = "";
    int kuk = 0;
    int eng = 0;
    int tot = 0;
    float avg = 0.0f;
 
    public MethodTest() { //기본생성자: 클래스 이름과 같은데 인자가 없는 생성자
                            //변수 초기화X heap 영역에 메모리만 할당하는 역할
    }
 
    public int getTot()    {
        return tot;
    }
 
    public float getAvg() {
        int avg_round = 0;
        avg_round = (int)(avg + 0.5); // 변형해서 반환할 수도 있음
        return float;
    }
 
    public void clacTot() {
        tot = kuk + eng;
    }
 
    public void calcAvg() {
        avg = tot / 2.0f;
    }
 
    public int setKuk(int kuk) {
        this.kuk = kuk;
    }
 
    public int setEng(int eng) {
        this.eng = eng;
    }
 
    public void prn()    {
        System.out.println("국어: " + mt.kuk);
        System.out.println("영어: " + mt.eng);
        System.out.println("총점: " + mt.tot);
        System.out.println("평균: " + mt.avg);
    }
}
 
public class MethodTestMain9 {
    public static void main(String[] args) {
        MethodTest mt = new MethodTest(); // 기본생성자 호출. 변수 재초기화는 setter사용
                                            //heap 영역에 메모리 
 
        mt.setKuk(95);
        mt.setEng(80);
        mt.calcTot();
        mt.calcAvg();
        System.out.println("총점: " + mt.getTot());
        System.out.println("평균: " + mt.getAvg());
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

 

 

 

 

 

 

<Static variable 예제>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 
class ScjpPass {
 
    int t1 = 0;
    int t2 = 0;
    int t3 = 0;
    int t4 = 0;
 
    static int BONUS = 100// 클래스 변수!!! 거의 상수를 만들 때 많이 쓴다.
                            //but, final이 붙지 않으면 재초기화 가능하다.
 
    public ScjpPass() { //기본생성자(인자X)
    }
 
    public ScjpPass(int t1, int t2, int t3, int t4) { // 생성자 오버로딩
        this.t1 = t1;
        this.t2 = t2;
        this t3 = t3;
        this t4 = t4;
    }
}
 
public class Scjp {
    public static void main(String args[])    {
        System.out.println("ScjpPass.BONUS: " + ScjpPass.BONUS); //클래스변수 호출: 클래스이름.변수
                                                                //인스턴스 생성하지 않아도 바로 호출 가능
        ScjpPass sp = new ScjpPass(85908070);
        System.out.println("sp.t1: " + Sp.t1);
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

*final: 변경할 수 없다. 클래스 변수를 상수로 만들 때 사용

 

 

<Static method 예제>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 
class SCWCD {
 
    int t1 = 0;
    int t2 = 0;
    int t3 = 0;
    int t4 = 0;
    static int BONUS = 100;
 
    public SCWCD() {
    }
 
    public SCWCD(int t1, int t2, int t3, int t4) {
        this.t1 = t1;
        this.t2 = t2;
        this t3 = t3;
        this t4 = t4;
    }
 
    public String Pass() {
        String msg = null;
        if(t1 > 65 && t2 >= 65 && t3 >= 65 && t4 >= 65) {
            msg = "축하합니다. 합격입니다.";
        } else {
            msg = "미안합니다. 불합격입니다.";
        }
        return msg;
    }
 
    public void static prLine() { //static 메소드 -> 인스턴스 생성 없이 실행 가능
        System.out.println("**************");
        System.out.println("    STUDY");
        System.out.println("        JAVA");
        System.out.println("**************");
    }
}
 
public class SCWCDmain {
    public static void main(String args[])    {
        SCWCD sc = new SCWCD();
        sc.t1 = 100;
        SCWCD.prLine();
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

 

 

 

 

<오버로딩(overloading)>

 

: 클래스 안에 생성자가 여러 개 있는 것을 말한다.(생성자는 heap에 메모리를 할당하는 역할)

-> 같은 이름의 함수에 여러가지 일을 시키는 것. 즉, 동일한 클래스 안에 같은 이름의 함수(메소드)를 인자의 개수나 형을 달리하면서 여러 번 선언(정의)하는 것을 말한다.
ex. 생성자 다섯 개: 힙 메모리 할당하는 종류가 다섯 가지, 즉 인스턴스 만드는 방법이 다섯 가지.  
인자 없이 만들 수도 있고, 인자 두 개 줘서 만들 수도 있다. 

 

1)인자 없는 생성자(기본 생성자): 각 변수 초기값 = 0 
2)생성자에 의한 초기화(인자 한 개 이상인 생성자)
3)setter를 통한 재초기화

'20.03 ~ 20.08 국비교육 > JAVA' 카테고리의 다른 글

변수 유효범위  (0) 2020.03.24
싱글톤(Singletone pattern), final  (0) 2020.03.22
Call by value vs Call by reference  (0) 2020.03.21
클래스 멤버 메소드  (0) 2020.03.21
클래스 구조  (0) 2020.03.21