Java/[국비] JAVA

[국비][JAVA] Class, Object이해_심화 예시

줌인. 2024. 5. 29. 23:49

▶ Class, Object 이해

https://zoooom-in.tistory.com/105

 

[국비][JAVA] Class, Object이해

▶ 클래스 도입 및 객체 이해하기https://zoooom-in.tistory.com/43 [김영한_자바기본][1.클래스와 데이터] 클래스 도입, 객체 이해하기(인스턴스) (p.15-23)Class는 설계도로, 객체(인스턴스)는 설계도를 구현

zoooom-in.tistory.com

 

각 배열 요소에 Student 객체를 생성하여 할당해야 함
- 이를 통해 배열 요소가 null이 아닌 실제 객체를 참조하기 때문
- 초기화: 배열 생성 시 각 요소는 null
- 이는 아직 객체가 생성되지 않았다는 뜻
- null 상태에서는 객체의 필드나 메서드에 접근할 수 없음
- 데이터 저장: 각 배열 요소에 Student 객체를 생성하여 할당해야, 이후에 학생 정보를 해당 객체에 저장할 수 있음

 

[오류 예시]

Student[] students = new Student[3];
// 이 상태에서 학생 정보에 접근하면 NullPointerException 발생
students[0].name = "John"; // 오류 발생

 

[정정코드 예시]

Student[] students = new Student[3];
for (int i = 0; i < students.length; i++) {
    students[i] = new Student(); // 객체 생성 및 배열에 할당
    students[i].name = "John";   // 정상적으로 접근 가능

 

- 배열은 동일한 타입의 여러 객체를 저장할 수 있음
- 객체를 직접 생성하지 않으면 null 상태로 남아 있음
- 이 상태에서 객체의 필드나 메서드에 접근하면 NullPointerException이 발생
∴ 배열을 생성한 후 각 요소에 객체를 생성하여 할당해야만 안전하게 데이터를 저장하고 사용할 수 있음

 

 


 

[Main코드 예시]

public class StudentMain {
    StudentController sc = new StudentController();
       sc.start();
}

 

[StudentController 예시]

public class StudentController {
    Student[] students = null; //Student 배열 type을 담는다.
    //추후 배열 출력이 필요하기 때문에 재사용성을 위해 별도 변수 선언
    Scanner sc = new Scanner(System.in);
    boolean flag = true;
    StudentService service = new StudentService();
       while (flag) {
        System.out.println("1. 학생정보입력 2.전체정보출력 3.학생검색 4.종료");
        int select = sc.nextInt();
        if (select == 1) {
            System.out.println("학생 정보를 입력하세요");
            students = service.makeStudent(); //학생의 정보가 들어있는 배열 생성
        } else if(select ==2) {
            System.out.println("전체 정보 출력 코드 작성");
            //학생의 정보가 들어있는 배열 값 출력
            for(int i=0; i < students.length;i++) {
                System.out.println(students[i].name);
                System.out.println(students[i].avg);
            }
        } else if(select==3) {
            System.out.println("학생 정보를 검색하는 코드 작성");
        } else if(select==4) {
            System.out.println("프로그램을 종료합니다.");
            flag = false;
        } else {
            System.out.println("다시 정확한 숫자를 입력해주세요");
            continue;
        }
    }
}

 

[StudentService 예시]

public class StudentService {
    public Student[] makeStudent() {//class타입의 배열
        Scanner sc = new Scanner(System.in);
        System.out.println("학생 수를 입력하세요 : ");
        int count = sc.nextInt();
        Student[] student = new Student[count]; //학생수를 정함
        //Student type이 들어갈 수 있는 배열이 만들어진 것 --> 현재 null
        //배열의 공간만 생성, 학생을 담을 수 있는 공간만 생성
        for (int i=0; i < student.length ; i++) {
            student[i] = new Student(); //N번째 배열에 Student type 객체 생성
            //학생을 생성하고, 배열의 공간에 전달
            //해당 부분은 Student타입만 들어갈 수 있음, 따라서 구체적으로 어떠한 학생이 있는지 만들어줌
            System.out.println("이름을 입력해주세요 : ");
            student[i].name = sc.next();
            System.out.println("번호를 입력해주세요 : ");
            student[i].num = sc.nextInt();
            System.out.println("국어 점수를 입력해주세요 : ");
            student[i].kor = sc.nextInt();
            System.out.println("영어 점수를 입력해주세요 : ");
            student[i].eng = sc.nextInt();
            System.out.println("수학 점수를 입력해주세요 : ");
            student[i].math = sc.nextInt();
            student[i].total = student[i].kor + student[i].eng + student[i].math;
            student[i].avg = student[i].total / 3.0;
        }
        return student; //학생의 정보 반환(여러명의 학생의 정보 = 같은 타입 = 배열화)
    }
}

 

[Student 예시]

package collection.ex;

public class Student {
    //선언하지 않았을 떄 초기값 -> 인스턴스변수(멤버변수) : 힙영역에 있는 것들 -> 기본으로 초기화
    int num; //0
    String name; //null
    int kor; //0
    int eng; //0
    int math; //0
    int total; //0
    double avg; //0.0

    //접근 제어자** + 그외 제어자(static) + void(반환값) + main(메서드 명) + (매개변수) {내용}
    public void info() { //객체가 있어야 해당 메서드가 실행됨
        //메인 메서드에서 호출하고,실행됨 -> main메서드 내 지역변수로 선언됨
        System.out.println("info가 실행됩니다.");
    }
}

 

[예시 이미지화]

 

728x90