본문 바로가기
Error Note

[Java] 포함 관계 구현 중 NullPointerException 발생

by 스응 2023. 2. 7.
728x90
728x90

#  관련 포스팅

  - 생성자 : https://young0105.tistory.com/29

 


java.lang.NullPointerException 원인

  ① new 키워드를 사용하지 않아, 메모리에 아직 로드되지 않은 경우

  ② . 연산자를 잘못 사용한 경우

 

에러 발생 코드

  - 포함 관계인 Student 클래스와 Subject 클래스 설계

  - Student 클래스에 Subject를 참조 자료형으로 사용한 멤버 변수(국어)를 생성함

#  Subject 클래스 파일

public class Subject {
	
    // 멤버변수 //
    String subjectName; // 과목 이름
    int score; // 과목 점수
	
}

# Student 클래스 파일

public class Student {

    // 멤버변수 //
    int studentId; // 번호
    int grade; // 학년
    String name; // 이름
    // Subject 클래스를 참조 자료형으로 받음
    Subject korea; // 국어

    // 생성자 //
    public Student(int studentId, int grade, String name) {
        this.studentId = studentId;
        this.grade = grade;
        this.name = name;
    }

    // 메서드 : 상태 확인 //
    public void showInfo() {
        System.out.println("**상태창**");
        System.out.println("이름 : " + this.name);
        System.out.println("학년 : " + this.grade);
        System.out.println("번호 : " + this.studentId);
        System.out.println(this.korea.subjectName + " 과목의 점수 : " + this.korea.score);
    }
}

#  main 함수 파일

public class MainTest1 {

	public static void main(String[] args) {
		
		// 1번, 3학년, 홍길동
		Student studentHong = new Student(1, 3, "홍길동");
		
		// studentHong의 멤버변수 korea에서 Subject 클래스의 멤버변수로 접근
		studentHong.korea.subjectName = "국어";
		studentHong.korea.score = 90;
		
		// 확인
		studentHong.showInfo();
				
	} // end of main

} // end of class

 

  - 컴파일 시점에는 문법적 오류가 생기지 않았으나, 실행하려고 하자 오류가 발생함

      → java.lang.NullPointerException는 런타임 에러에 속함

 

#  오류 원인

 

  - Subject 클래스의 멤버변수인 'subjectName', 'score'에 접근해야 하는데, Subject가 메모리에 로드되지 않았음

      → 해결 방안 : 'new' 키워드를 사용해서 클래스 내부 or 외부에서 초기화

 


코드 수정

#  Student 클래스 파일

public class Student {

    // 멤버변수 //
    int studentId; // 학번
    int grade; // 학년
    String name; // 이름
    Subject korea; // 국어

    // 생성자 //
    public Student(int studentId, int grade, String name) {
        this.studentId = studentId;
        this.grade = grade;
        this.name = name;

        // 클래스 내부에서 초기화 //
        this.korea = new Subject();
    }

    // 메서드 //
    public void showInfo() {
        System.out.println("**상태창**");
        System.out.println("이름 : " + this.name);
        System.out.println("학년 : " + this.grade);
        System.out.println("학번 : " + this.studentId);
        System.out.println(this.korea.subjectName + " 과목의 점수 : " + this.korea.score);
    }
    
}

 

320x100
반응형

댓글