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

2023. 2. 7. 00:27·Error Note
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
반응형
저작자표시 비영리 변경금지

'Error Note' 카테고리의 다른 글

[MSSQL] DB에 중문 데이터 삽입 시 글자가 깨지는 문제  (1) 2023.12.21
[Spring Boot] MyBatis xml 파일에서 WHERE ... LIKE 문 사용하기  (0) 2023.04.26
[JSP] JSTL 태그 안에 HTML 주석 작성 시 오류  (0) 2023.04.14
[Java/Swing] getText()를 사용할 수 없는 JPasswordField에서 값 가져오기  (0) 2023.03.12
[Java] 로또 게임 구현 중 NullPointerException 발생  (0) 2023.02.19
'Error Note' 카테고리의 다른 글
  • [Spring Boot] MyBatis xml 파일에서 WHERE ... LIKE 문 사용하기
  • [JSP] JSTL 태그 안에 HTML 주석 작성 시 오류
  • [Java/Swing] getText()를 사용할 수 없는 JPasswordField에서 값 가져오기
  • [Java] 로또 게임 구현 중 NullPointerException 발생
스응
스응
    반응형
    250x250
  • 스응
    이서영의 개발 블로그
    스응
  • 전체
    오늘
    어제
  • 글쓰기 관리
    • 분류 전체보기 (383)
      • Java (134)
        • Base (54)
        • Spring Boot (37)
        • JSP (16)
        • Swing (GUI) (20)
        • Design Pattern (7)
      • C# (13)
      • PHP (18)
      • SQL (27)
      • Vue.js (10)
      • Tailwind CSS (4)
      • TypeScript (7)
      • HTML & CSS (27)
      • JavaScript (26)
      • jQuery (10)
      • Android (3)
      • - - - - - - - - - - - - - - (0)
      • Hotkeys (5)
      • CS (30)
      • etc. (13)
      • Error Note (14)
      • Team Project (24)
        • Airlines Web Project (12)
        • University Web Project (6)
        • Strikers 1945 GUI Project (6)
      • My Project (18)
        • Library Web Project (8)
        • Pet Shopping Mall GUI Project (10)
  • 블로그 메뉴

    • Home
    • Write
  • 링크

    • 깃허브
  • 공지사항

  • 인기 글

  • 태그

    http
    zapier
    java
    git
    Codeigniter
    Wordpress
    티스토리챌린지
    면접
    Hotkeys
    Swing
    jQuery
    tailwindcss
    js
    C#
    vuejs
    jsp
    php
    오블완
    Android
    HTML
    typeScript
    errorNote
    CSS
    cs
    SQL
    개발일지
    SpringBoot
    SEO
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.0
스응
[Java] 포함 관계 구현 중 NullPointerException 발생
상단으로

티스토리툴바