자바 초보부터 B형까지9 -class 생성하기 필수-

1. class

 

두 학생의 국어 영어 수학 점수가 (90,80,80), (80,70,60)이라고 한다면, 이를 코드로 표현한다면 어떻게 해야할까?

 

가장 쉬운 방법은 6개의 변수를 만드는 것이다.

 

int kor1 = 90, eng1 = 80, math1 = 90;
int kor2 = 80, eng2 = 70, math2 = 60;

 

하지만 학생 수가 많아질수록 변수의 수는 그만큼 증가하니 상당히 귀찮은 작업이 된다.

 

이런 경우 하나의 학생을 지칭하는 새로운 형태를 정의하며, 

 

그 형태를 이루기 위한 (국어, 영어, 수학) 점수 세트를 정의할 수 있을 것이다.

 

이를 class라고 부르고 자바에서 class는 다음과 같이 정의할 수 있다.

 

class Student {
    int kor, eng, math;
    
    public Student(int kor, int eng, int math){
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }
};

 

 

public Student는 Student 클래스의 형태를 정의하는 생성자(constructor)

 

인자로 넘어오는 kor, eng, math는 현재 학생의 kor, eng, math라는 값이 되며 kor, eng, math는 각각 멤버 변수라고 부른다

 

참고로 생성자의 이름은 class의 이름과 같아야한다.

 

또한 생성자 앞에는 아무런 반환타입도 명시하지 않는다.

 

위에서 정의한 클래스를 이용한다면 다음과 같이 하나의 학생 정보를 관리하는 코드를 작성할 수 있다.

 

Student student1 = new Student(90,80,90);

System.out.println(student1.kor);  // 90
System.out.println(student1.eng);  // 80
System.out.println(student1.math); // 90

 

Student 클래스를 마치 함수를 호출하는 것처럼, 인자로 값을 넘겨주어 해당 값을 가지는 하나의 학생 객체(instance)를 생성한다.

 

특히 객체 생성시 new라는 키워드를 반드시 붙여주자.

 

현재 해당 객체는 kor, eng, math라는 멤버변수를 가지고 이 값들을 조회하고 싶다면..

 

객체이름.멤버변수이름 형태로 조회하면 된다

 

이처럼 필요하면 원하는 형태의 class를 정의하여, 해당 class를 이용해 원하는 형태 단위로 값을 관리할 수 있다.

 

참고로 자바는 tuple이 없다...

 

 

2. 객체 초기값

 

객체 생성시에 생성자가 정의되어있는데, 아무런 인자를 넘겨주지 않으면 에러가 난다

 

class Student {
    int kor, eng, math;

    public Student(int kor, int eng, int math){
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }
};

public class Main {
    public static void main(String[] args) {
        Student student1 = new Student();
    }
}
>>  error: constructor Student in class Student cannot be applied to given types;

 

 

자바에서는 함수 인자의 초기값을 설정하기가 어렵다.

 

그래서 method overriding을 이용해서.. 동일한 이름의 생성자를 2개 만드는 것으로 다음과 같이 해결할 수 있다.

 

 

class Student {
    int kor, eng, math;

    public Student(){
        this.kor = 0;
        this.eng = 0;
        this.math = 0;
    }

    public Student(int kor, int eng, int math){
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }
};

public class Main {
    public static void main(String[] args) {
        Student student1 = new Student(90, 80, 90); // 넘어간 값을 사용
        System.out.println(student1.kor);  // 90
        System.out.println(student1.eng);  // 80
        System.out.println(student1.math); // 90

        Student student2 = new Student();  // 값이 넘어가지 않는 생성자를 이용
        System.out.println(student2.kor);  // 0
        System.out.println(student2.eng);  // 0
        System.out.println(student2.math); // 0
    }
}

 

국어, 영어, 수학점수를 인자로 넘겨주는 경우, 2번째 인자가 정의된 메소드를 사용하고

 

인자로 넘겨주지 않으면  인자가 정의되지 않은 첫번째 메소드를 사용하게 된다

 

객체에 이미 들어있는 값은 어떻게 변경할까?

 

그냥 (객체이름).(변수이름) = 바꿀 값;으로 바꿀 수 있다

 

class Student {
    int kor, eng, math;

    public Student(){
        this.kor = 0;
        this.eng = 0;
        this.math = 0;
    }

    public Student(int kor, int eng, int math){
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }
};

public class Main {
    public static void main(String[] args) {
        Student student2 = new Student();  // 값이 넘어가지 않는 생성자를 이용
        System.out.println(student2.kor);  // 0
        System.out.println(student2.eng);  // 0
        System.out.println(student2.math); // 0

        student2.kor = 90;
        student2.eng = 80;
        student2.math = 90;

        System.out.println(student2.kor);  // 90
        System.out.println(student2.eng);  // 80
        System.out.println(student2.math); // 90
    }
}

 

3. 객체를 원소로 가지는 배열

 

객체를 원소로 가지는 배열은 어떻게 생성할까?

 

지금 너가 생각하는게 맞다

 

Student 클래스를 원소로 가지는 배열은 Student[] arr = new Student[5];  이런식으로 가능하다

 

import java.util.Scanner;

class Student {
    int kor, eng, math;

    public Student() {
        this.kor = 0;
        this.eng = 0;
        this.math = 0;
    }

    public Student(int kor, int eng, int math){
        this.kor = kor;
        this.eng = eng;
        this.math = math;
    }
};

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 

        Student[] students = new Student[5];
        for(int i = 0; i < 5; i++) {
            int kor = sc.nextInt();
            int eng = sc.nextInt();
            int math = sc.nextInt();
            students[i] = new Student(kor, eng, math);
        }

        Student student3 = students[2];    // 세 번째 학생 정보
        System.out.print("student3: ");
        System.out.print(student3.kor + " ");
        System.out.print(student3.eng + " ");
        System.out.print(student3.math + " ");
    }
}


>> 90 80 90
   20 80 80
   90 30 60
   60 10 50
   80 20 10

student3: 90 30 60
TAGS.

Comments