본문 바로가기

IT/Java

08_클래스 : 필드, 생성자, 메소드

01. 클래스란

- 어떤 객체를 메모리에서 사용하기 위해서는 먼저 그 객체를 만들어야 한다. 객체를 만들기 위해 필요한 설계도가 클래스이다.

- 모든 클래스는 반드시 하나 이상의 생성자를 가지고 있다(생성자는 오버로딩 될 수 있다).

 

02. 클래스의 구성 멤버

- 클래스는 필드, 생성자, 메소드로 구성되어 있다. 자세한 내용은 아래에서 살펴본다.

 

1) 필드 

- 객체의 고유 데이터, 상태 정보를 저장하는 곳

- 블록을 벗어나면 메모리에서 제거되는 변수와 달리 생성자와 메소드 전체에서 사용되며 객체가 소멸하지 않는 한 계속 존재한다.

 

필드는 선언과 동시에 초기화 될 수도 있고 그렇지 않을 수도 있다.

1
2
3
4
5
6
7
8
9
10
public class Car {
    //필드
    String company = "부가티";
    String model = "시론";
    String color = "블루";
    int maxSpeed = 420;
    int speed;
    
}
 
 

 

클래스의 필드는 new 연산자를 통해 생성한 객체를 통해서만 접근할 수 있다. 

초기화되지 않은 int형 필드의 기본 값은 0이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class CarExample {
    public static void main(String[] args) {
        //객체 생성
        Car myCar = new Car();
        
        //필드값 읽기
        System.out.println("제작회사 : " + myCar.company);
        System.out.println("모델명 : " + myCar.model);
        System.out.println("색상 : " + myCar.color);
        System.out.println("최대속도 : " + myCar.maxSpeed);
        System.out.println("기존속도 : " + myCar.speed);
        
        //필드값 변경
        myCar.speed = 60;
        System.out.println("현재속도 : " + myCar.speed);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

2) 생성자

- new연산자로 호출되며 객체 생성시 초기화를 담당한다. 필드를 초기화하고 메소드를 호출함으로써 객체를 사용할 준비를 한다. 클래스 이름으로 되어 있고 리턴 타입은 없다.

- 모든 클래스는 매개변수가 없는 기본생성자를 가지고 있다. 생성자는 오버로드 될 수 있다.

- 기본생성자의 선언은 생략할 수 있지만 다른 생성자로 오버로드 될 경우 외부에서 사용할 수 없다.

 

 

CASE 1:

- 기본생성자  : 생략

- 다른 생성자 : 있음

1
2
3
4
5
6
7
8
 
public class Car {
 
    Car(String color, int cc){
    }
 
}
 

기본생성자를 사용할 수 없다.

1
2
3
4
5
6
7
8
9
10
public class CarExample {
public static void main(String[] args) {
 
//    Car myCar = new Car();    //다른 생성자가 있는데 기본생성자를 명시적으로 선언해주지 않으면 여기서 사용할 수 없다
    Car myCar = new Car("검정"3000);
 
        
}
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

CASE 2:

- 기본생성자 : 선언

- 다른 생성자 : 있음

1
2
3
4
5
6
7
8
9
10
11
public class Car {
    
 
    Car(){
        
    }
    Car(String color, int cc){
        
    }
    
}
 

 두 생성자 모두 정상적으로 사용할 수 있다.

1
2
3
4
5
6
7
8
9
10
public class CarExample {
public static void main(String[] args) {
    //2번
    Car myCar = new Car();    //명시적으로 선언해줬으므로 사용 할 수 있다
    Car myCar2 = new Car("검정"3000);
 
            
}
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

CASE 3:

- 기본생성자 : 생략

- 다른 생성자 : 없음

1
2
3
4
public class Car {
    
    
}
cs

 

아무 문제 없이 기본생성자를 사용할 수 있다.

1
2
3
4
5
6
7
8
9
10
public class CarExample {
public static void main(String[] args) {
 
    Car myCar = new Car();    //다른 생성자가 없을 때는 기본생성자를 명시적으로 선언하지 않아도 사용 할 수 있다.
    
 
            
}
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

한편, 생성자에서 this를 이용하여 중복코드를 줄일 수 있다.

 

다음과 같은 Car 클래스가 있다.

 

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

public class Car {

    //필드

    String company = "현대자동차";

    String model;

    String color;

    int maxSpeed;

    

    //생성자

    Car(){

        

    }

    

    Car(String model){

        this(model, "은색"250);    //default color : 은색

    }

    

    Car(String model, String color){    //다른 색상은 이 생성자로 만듦

        this(model, color, 250);    //default maxSpeed : 250

    }

    

    Car(String model, String color, int maxSpeed){    //다른 최고속도는 이 생성자로 만듦

        this.model = model;

        this.color = color;

        this.maxSpeed = maxSpeed;

    }

 

}

http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

 

250km/h의 최고속도를 가진 은색 자동차를 제일 많이 생산한다고 가정한다.

만약 #21의 생성자를 사용한다면 

Car myCar1 = new Car("그랜저""은색"250);
Car myCar2 = new Car("소나타""은색"250);
Car myCar3 = new Car("제네시스""은색"250); 
 
 

..... 이런 식으로 매 번 "은색", 250 이라는 매개변수를 반복적으로 넣어줘야 한다.

 

그러나 #13의 생성자를 사용하여 default로 "은색"과 250이라는 값을 넣어두면

Car myCar1 = new Car("그랜저");
Car myCar2 = new Car("소나타"):
Car myCar3 = new Car("제네시스");
 

.... 이런 식으로 모델명만 입력하면 자동으로 250km/h의 최고속도를 가진 은색 자동차 객체가 만들어진다.

 

색깔이나 최고속도가 다른 자동차를 만들고 싶으면 다른 생성자를 이용하면 된다.

 

3) 메소드
- 객체의 동작에 해당한다. 객체 간의 데이터 전달 수단이다.
 
메소드를 만들 때 매개변수의 개수를 모르는 경우가 있다.
이 때, 매개변수를 배열의 형태로 선언하면 되는데, 두 가지 방법이 있다.
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//매개변수의 수를 모르면 배열형태로 선언하면 된다.
public class Computer {
    
    //방법1
    int sum1(int[] values) {    
        int sum = 0;
        for(int i=0; i < values.length; i++) {
            sum += values[i];
        }
        return sum;
    }
    
    //방법2
    int sum2(int ... values) {
        int sum = 0;
        for(int i=0; i<values.length; i++) {
            sum += values[i];
        }
        return sum;
    }
 
}
 
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
public class ComputerExample {
    public static void main(String[] args) {
        Computer myCom = new Computer();
 
        //초기화된 배열형 변수를 넣어줌
        int[] values1 = {1,2,3};
        int result1 = myCom.sum1(values1);
        System.out.println("result1 : " + result1);
        System.out.println();
        
        int[] values2 = {1,2,3};
        int result2 = myCom.sum2(values2);
        System.out.println("result2 : " + result2);
        System.out.println("-----------------------------");
        //배열을 선언하면서 직접 넣어줌
        int result3 = myCom.sum1(new int[] {1,2,3,4,5});
        System.out.println("result3 : " + result3);
        System.out.println();
        
        int result4 = myCom.sum2(new int[] {1,2,3,4,5});
        System.out.println("result4 : " + result4);
        System.out.println("-----------------------------");
        
        //int 값을 콤마로 나열하여 그냥 넣어줌
        int result5 = myCom.sum2(1,2,3);
//        int result6 = myCom.sum1(1,2,3);    //... 에만 사용 가능
        System.out.println("result3 : " + result3);
 
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter