20.03 ~ 20.08 국비교육/JAVA

클래스 멤버 메소드

찹키리 2020. 3. 21. 22:24

<함수 만들기★★★> =메소드 정의하기(처음엔 외우는 수밖에 없다.)



//접근자 반환형 함수명( [받는 인자들]: 인자는 0개 이상, 생략 가능한 인자는 []로 묶음 ) {


받은 인자 처리;

return 반환값; ---> 생략 가능(반환값이 없는 함수도 있기 때문 ex.void)

}// -> 함수영역(메소드 영역)

 

 

 

 

규칙1. 함수는 정의만으로 실행되지 않고, 호출(call)할 때 실행된다.

규칙2. 함수(메소드)는 call할 때마다 실행된다(가장 작은 단위의 재활용).

규칙3. 호출하는 쪽 인자는 실인자, 호출받는 쪽 인자는 가인자(실인자를 받음)
실인자와 가인자는 데이터 형이 일치해야 한다.

규칙4. 반환형과 반환값은 데이터 형이 일치한다.

규칙5. 함수는 실행될 때 stack영역을 사용한다.

규칙6. 리턴(반환)이 없는 메소드는 void다.
-> void는 자신이 일을 시작하고 마무리(println까지)★
-> return은 일의 중간 계산을 처리, println은 다른 클래스에서 처리해줌★

규칙7. 함수는 실행 후 메모리를 바로(자동) 반환한다.(메모리에서 지워진다) -> stack영역이기 때문

 

 

 

main: 가상머신에 의해 자동으로 호출되는 변수
heap: 데이터(변수) 저장 영역
stack: 메소드가 실행되고 반환되는 영역

jvm: 가상머신, 실행상태
jre: 가상머신의 실행환경 만들어준다.(java runtime environment)
jdk: 컴파일, 개발환경

 

 

<(1)함수 정의 예제>

 

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
 
public class MethodTest {
 
    //처리 메소드가 없는 경우
    String name = "";
    int kuk = 0;
    int eng = 0;
    int tot = 0;
    float avg = 0.0f;
 
    public static void main(String[] args) {
        MethodTest mt = new MethodTest(); // 생성자를 호출해 인스턴스를 만든다.
 
        mt.kuk = 100;
        mt.eng = 90;
 
        mt.tot = mt.kuk + mt.eng;
        mt.avg = mt.tot / 2;
 
        System.out.println("국어: " + mt.kuk);
        System.out.println("영어: " + mt.eng);
        System.out.println("총점: " + mt.tot);
        System.out.println("평균: " + mt.avg);
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

처리 메소드 없이 만든 클래스

 

 

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
 
public class MethodTest2 {
 
    String name = "";
    int kuk = 0;
    int eng = 0;
    int tot = 0;
    float avg = 0.0f; //멤버 변수
 
    public void clacTot() {
        tot = kuk + eng;
    }
 
    public void calcAvg() {
        avg = tot / 2.0f;
    }
 
    public void prn()    {
        System.out.println("국어: " + mt.kuk);
        System.out.println("영어: " + mt.eng);
        System.out.println("총점: " + mt.tot);
        System.out.println("평균: " + mt.avg);
    }
 
    public static void main(String[] args) {
        MethodTest2 mt = new MethodTest(); // 인스턴스 생성
 
        mt.kuk = 100;
        mt.eng = 90;
        mt.calcTot();
        mt.calcAvg();
        mt.prn();
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

함수를 이용해 만든 클래스

-> 연산 등 복잡한 작업들을 모두 메소드화 시켜 main 영역에서는 변수 초기화와 클래스만 호출하면 되도록 만들었다. 객체지향의 특성인 재활용성을 활용하고 있는 클래스

 




<생성자>

 

1. 클래스 이름과 동일

 

2. 반환형(void)이 없음

 

----------주 역할----------
3. ★new와 함께 사용 ---> 인스턴스 생성에 관여
4. 인자를 받아 멤버 변수를 초기화
----------주 역할----------

 

5. 생성자에 간단한 로직을 추가할 수 있다.

 

6. ★this★는 해당 인스턴스를 가리키는 키워드
this -> 전역변수, this x -> 지역변수

 

7. 지역변수를 받아서 멤버변수를 초기화 ---> 인스턴스 생성 시 멤버변수 초기화, ★변수 초기화 과정이 없다★

 

8: "new": 인스턴스/배열 만들 때만 나온다 ---> 힙 영역에 메모리 할당★

-처리 클래스, 실행 클래스가 동일 폴더에 있는 경우, import 생략가능★
-영역 나누는 기호: { }

 

9. 객체를 만들 때만 사용한다.

 

 

<(2)생성자 예제>

 

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
 
public class MethodTest3 {
 
    String name = "";
    int kuk = 0;
    int eng = 0;
    int tot = 0;
    float avg = 0.0f; //멤버 변수
 
    public MethodTest3(int kuk, int eng) { //인자가 두 개인 생성자. 생성자 이름은 클래스명과 동일
        this.kuk = kuk;
        this.eng = eng;
    }
 
    public void clacTot() {
        tot = kuk + eng;
    }
 
    public void calcAvg() {
        avg = tot / 2.0f;
    }
 
    public void prn()    {
        System.out.println("국어: " + mt.kuk);
        System.out.println("영어: " + mt.eng);
        System.out.println("총점: " + mt.tot);
        System.out.println("평균: " + mt.avg);
    }
 
    public static void main(String[] args) {
        MethodTest3 mt = new MethodTest3(10090);
        //생성자의 역할: 지역변수 kuk을 받아, 멤버변수 kuk을 초기화한다.
        //인스턴스 생성 시 멤버변수를 초기화할 수 있다.
 
        mt.calcTot();
        mt.calcAvg();
        mt.prn();
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

 

 

 

 

<getter>

 

getter: 멤버변수를 호출하는 곳으로 리턴한다. 메소드 이름은 get변수로 지정한다.

 

-형식-
int tot;
public int getTot() {
return (this.)tot;
}

실수나 의도적으로 변수를 초기화시키는 것을 방지하려는 목적 -> 은닉화

클래스 바깥에서는 변수를 호출할 수 없기 때문에 변수를 호출하는 메소드를 만든 것.

1)변수의 접근자는 private(클래스 밖에서는 접근 불가)
2)메소드의 접근자는 public(어디서든 접근 가능)

 

 

<(3)getter 예제>

 

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
 
public class MethodTest6 {
 
    String name = "";
    int kuk = 0;
    int eng = 0;
    int tot = 0;
    float avg = 0.0f; //멤버 변수
 
    public MethodTest6(int kuk, int eng) {
        this.kuk = kuk;
        this.eng = eng;
    }
 
    public int getTot()    {
        return tot;
    }
 
    public float getAvg() {
        return float;
    }
 
    public void clacTot() {
        tot = kuk + eng;
    }
 
    public void calcAvg() {
        avg = tot / 2.0f;
    }
 
    public void prn()    {
        System.out.println("국어: " + mt.kuk);
        System.out.println("영어: " + mt.eng);
        System.out.println("총점: " + mt.tot);
        System.out.println("평균: " + mt.avg);
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

처리 클래스

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
public class MethodTestMain6 {
 
    public static void main(String[] args) {
 
        MethodTest6 mt = new MethodTest6(10090);
 
        mt.calcTot();
        mt.calcAvg();
        mt.prn();
 
        int tot = mt.getTot();
        float avg = mt.getAvg();
 
        System.out.println("총점: "    + tot);
        System.out.println("평균: "    + avg);
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

실행 클래스

 

 

 

 

<setter>

 

setter: 메소드를 통해 멤버변수를 초기화한다. 메소드 이름은 set변수로 지정한다.

 

getter와 유사한 기능 -> 은닉화

*실무에서 변수는 무조건 private. 조작불가능하게 만드는 게 일반적이다.

 

-형식-

int kuk;

public void setTot(int kuk) {

this.kuk = kuk;

}

 

*void는 반환 '안'한다는 뜻 = no return

 

 

<(4)setter 예제>

 

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
 
public class MethodTest7 {
 
    String name = "";    int kuk = 0;
    int eng = 0;
    int tot = 0;
    float avg = 0.0f;
 
    public MethodTest7(int kuk, int eng) {
        this.kuk = kuk;
        this.eng = eng;
    }
 
    public int getTot()    {
        return tot;
    }
 
    public float getAvg() {
        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);
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

처리 클래스

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
public class MethodTestMain7 {
 
    public static void main(String[] args) {        
        
        MethodTest7 mt = new MethodTest7(10090);
        mt.calcTot();
        mt.calcAvg();
        mt.prn();
 
        mt.setKuk(70);
        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

실행 클래스

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

클래스 JVM 메모리 운영, Static variable과 Method  (0) 2020.03.22
Call by value vs Call by reference  (0) 2020.03.21
클래스 구조  (0) 2020.03.21
배열  (0) 2020.03.21
7. 제어문 - 반복문(while문, for문)  (0) 2020.03.21