본문

[2017.08.06] 07. 왜 클래스 멤버를 사용할까?

결과적으로 '공통사항을 중복없이 선언, 사용하기 위해' 이다.



예를 들어 생각해보자.


Heepie네 가족은 공통적으로 집에 들어가기 위한 집 비밀번호를 알고 있고, 모두 각자의 방법으로 밥을 지을 수 있다.


이를 자바로 구현하면 다음과 같다.

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
class HeepieFamily {
    private int password = 1234;
    private int amountOfRice;
    private int water;
    
    public int getPassword() {
        return password;
    }
 
    public void setPassword(int password) {
        this.password = password;
    }
 
    void makeRice (int amountOfRice, int water) {
        this.amountOfRice = amountOfRice;
        this.water = water;
        System.out.println("밥 " + amountOfRice + "g과 물 " + water + "ml로 밥을 짓습니다.");
    }
}
 
public class Main {
    public static void main(String[] args) {
        HeepieFamily member1 = new HeepieFamily();
        HeepieFamily member2 = new HeepieFamily();
        HeepieFamily member3 = new HeepieFamily();
        HeepieFamily member4 = new HeepieFamily();
        
        // 비밀번호 변경 시, 다시 설정 -> 유지보수가 불편함 
        member1.setPassword(5678);
        member2.setPassword(5678);
        // 실수 할 가능성 또한 존재 
        member3.setPassword(8765);
        member4.setPassword(5678);
        
        member1.makeRice(100100);
        member2.makeRice(200200);
        member3.makeRice(150150);
        member4.makeRice(130130);
    }
}
cs

비밀번호의 경우, 모든 멤버가 공통적으로 사용하는 변수이다.

각각 멤버가 종이에 적어 가지고 있는 것(각 변수에 담아 넣는 것)보다 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class HeepieFamily {
    // 'static'키워드로 password 클래스 변수 선언 
    static int password = 1234;
    private int amountOfRice;
    private int water;
    
    public int getPassword() {
        return password;
    }
 
    public void setPassword(int password) {
        this.password = password;
    }
 
    void makeRice (int amountOfRice, int water) {
        this.amountOfRice = amountOfRice;
        this.water = water;
        System.out.println("밥 " + amountOfRice + "g과 물 " + water + "ml로 밥을 짓습니다.");
    }
}
 
public class Main {
    public static void main(String[] args) {
        HeepieFamily member1 = new HeepieFamily();
        HeepieFamily member2 = new HeepieFamily();
        HeepieFamily member3 = new HeepieFamily();
        HeepieFamily member4 = new HeepieFamily();
        
        // 멤버1이 비밀번호 변경 시, 모든 멤버에게 적용된다. 
        member1.setPassword(5678);
        // 클래스 이름을 통해 직접 접근도 가능하다. 
        HeepieFamily.password = 5678;
        
        // print '5678'
        System.out.println(member2.getPassword());
        
        member1.makeRice(100100);
        member2.makeRice(200200);
        member3.makeRice(150150);
        member4.makeRice(130130);
    }
}
cs


이렇게 멤버가 사용하는 공통 변수, 메소드의 경우 static을 통해 클래스 멤버로 선언하면 중복을 제거 할 수 있다.

공유

댓글