[Java] 'non-static method cannot be referenced from a static context' 오류 해결 방법

[Java] 'non-static method cannot be referenced from a static context' 오류 해결 방법

Java
민호이 민호이 2025. 1. 13. 18:15
목차
  1. 1. 문제 개요
  2. 2. 오류 원인
  3. 2.1 Static과 Non-static의 차이
  4. 2.2 Static 메서드에서 Non-static 메서드를 호출할 수 없는 이유
  5. 3. 해결 방법
  6. 3.1 객체 생성 후 Non-static 메서드 호출
  7. 3.2 메서드를 Static으로 선언
  8. 3.3 설계 개선
  9. 4. 결론
  10. Reference

1. 문제 개요

Java에서 개발을 진행하다 보면 "non-static method cannot be referenced from a static context"라는 오류 메시지를 마주할 수 있습니다. 이 오류는 정적(static) 메서드에서 비정적(non-static) 메서드를 호출하려 할 때 발생합니다. 이 문서에서는 해당 오류의 원인과 해결 방법을 단계별로 설명합니다.


2. 오류 원인

2.1 Static과 Non-static의 차이

Java는 객체 지향 프로그래밍 언어로, Static과 Non-static 요소를 구분합니다.

Static (정적)

  • 클래스 레벨에서 존재하며, 특정 객체와 관계가 없습니다.
  • 객체를 생성하지 않고도 호출할 수 있습니다.
public class Example {
public static void printStatic() {
System.out.println("This is static.");
}
}
Example.printStatic(); // 객체 생성 없이 호출 가능

Non-static (비정적)

  • 객체 인스턴스에 종속되어야만 존재합니다.
  • 객체의 상태(instance variables)를 참조하거나 조작할 때 사용됩니다.
public class Example {
public void printNonStatic() {
System.out.println("This is non-static.");
}
}
Example obj = new Example();
obj.printNonStatic(); // 객체 생성 후 호출 가능

2.2 Static 메서드에서 Non-static 메서드를 호출할 수 없는 이유

Static 메서드는 객체와 독립적으로 동작하기 때문에 Non-static 메서드와 객체 상태(instance variables)에 접근할 수 없습니다.

예제: 오류 발생 코드

public class Example {
private String message = "Hello";
public String getMessage() { // Non-static 메서드
return message;
}
public static void main(String[] args) {
// Error: Non-static method cannot be referenced from a static context
System.out.println(getMessage());
}
}
  • 발생 원인:
    main() 메서드는 Static으로 선언되었으며, Static 메서드는 특정 객체에 종속되지 않으므로 Non-static 메서드 getMessage()를 호출할 수 없습니다.

3. 해결 방법

3.1 객체 생성 후 Non-static 메서드 호출

Non-static 메서드를 호출하려면 객체를 생성해야 합니다.

수정된 코드

public class Example {
private String message = "Hello";
public String getMessage() {
return message;
}
public static void main(String[] args) {
Example obj = new Example(); // 객체 생성
System.out.println(obj.getMessage()); // 정상 작동
}
}

3.2 메서드를 Static으로 선언

Non-static 메서드가 특정 객체 상태에 의존하지 않는다면 Static 메서드로 선언할 수 있습니다.

수정된 코드

public class Example {
private static String message = "Hello";
public static String getMessage() { // Static 메서드로 선언
return message;
}
public static void main(String[] args) {
System.out.println(getMessage()); // 정상 작동
}
}

3.3 설계 개선

클래스 설계 시 Static과 Non-static의 역할을 명확히 구분해야 합니다.

  • Static 메서드: 공통 기능(유틸리티 메서드 등)에 사용.
  • Non-static 메서드: 객체 상태를 다루거나 변경할 때 사용.

4. 결론

Java에서 "non-static method cannot be referenced from a static context" 오류는 객체 지향 프로그래밍의 원칙을 지키기 위한 것입니다. Static과 Non-static의 개념을 올바르게 이해하고 코드 설계 시 이를 적절히 구분하면 해당 오류를 방지할 수 있습니다.

 

Reference

https://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static

저작자표시 비영리 변경금지
  1. 1. 문제 개요
  2. 2. 오류 원인
  3. 2.1 Static과 Non-static의 차이
  4. 2.2 Static 메서드에서 Non-static 메서드를 호출할 수 없는 이유
  5. 3. 해결 방법
  6. 3.1 객체 생성 후 Non-static 메서드 호출
  7. 3.2 메서드를 Static으로 선언
  8. 3.3 설계 개선
  9. 4. 결론
  10. Reference
'Java' 카테고리의 다른 글
  • [Java] JUnit으로 Java 클래스의 private 메서드와 필드를 테스트하는 방법
  • [Java] "java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException" 해결 방법: Java 9/10/11 지
  • [Java] 자바의 스택오버플로우 (StackOverflowError): 원인과 해결방법 완벽 분석
  • [Java] Getters와 Setters를 사용하는 이유와 장점, 쓰는 이유!
민호이
민호이
민호이
ChungCODE
민호이
전체
오늘
어제
  • Categories (128)
    • 스포츠 (6)
    • 인공지능 (5)
    • 주식 (6)
      • 경제 주식 전망 (5)
      • ETF (9)
    • CSAPP (4)
      • Lab Session (4)
      • Concepts (0)
    • C (19)
    • Java (24)
    • Rust (44)
      • Concepts (27)
      • Libraries (17)
    • PS (2)
    • 국내 소식 (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 최소공배수
  • 유클리드 호제법
  • 알고리즘
  • 최대공약수
  • 코드업
  • 수학
  • c++
  • C

최근 댓글

최근 글

반응형
hELLO · Designed By 정상우.v4.2.1
민호이
[Java] 'non-static method cannot be referenced from a static context' 오류 해결 방법
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.