이제부터 본격적으로 PS 공부를 시작하려고, 같이 공부하던 스터디 깃 레포를 딱 클론 받고, 예전에 적었던 자바 코드를 딱 적은 순간..!
package programmers.코딩_기초_트레이닝;
public class flag에_따라_다른_값_반환하기 {
class Solution {
public static int solution(int a, int b, boolean flag) {
return flag ? a + b : a - b;
}
}
public static void main(String[] args) throws Exception {
int answer = Solution.solution(-4,7,false);
System.out.println(answer);
}
}
오류가 발생했다.
시작부터 내 기분을 망쳐버린 이 괘씸한 빨간 문구를 어떻게 지울지 생각해봐야겠다.
문구에 따르면 `static` 이라는 문구가 constant variable declaration 에서만 가능하다는 것인데,, 어떤 의미일지 좀더 찾아보자.
문제 해결 자체는 어렵지 않았다.
오류를 구글에 치자마자 가장 상위에 떴던 스택오버 플로우답변을 찾아가보자.
Modifier static is only allowed in constant variable declarations
I have an inner class that stores the info of the controls I'm using for a game, now I want to store a static ArrayList in it that holds all the names of the controls. But I am getting this error: ...
stackoverflow.com
글쓴이의 경우는 나와 살짝 다르게, 클래스 안에서, 클래스의 property를 static하게 선언하면서 해당 오류가 발생했다.
답변:
An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields
답변을 분석해 보면,
1. inner class 는 static으로 선언되지 않은 nested 된 클래스이다.
2. inner class 는 static 생성자 혹은 멤버 인터페이스를 선언하지 않는다
3. inner class는 static 멤버 (상수 제외) 를 선언하지 않는다.
로 간추릴 수 있다.
좀 돌아가는 말인 것 같지만, 코드를 다시 보면
package programmers.코딩_기초_트레이닝;
public class flag에_따라_다른_값_반환하기 {
class Solution {
public static int solution(int a, int b, boolean flag) {
return flag ? a + b : a - b;
}
}
public static void main(String[] args) throws Exception {
int answer = Solution.solution(-4,7,false);
System.out.println(answer);
}
}
Solution 이라는 클래스는 nested 클래스이며, static 하기 때문에 inner Class로 분류가 된다.
inner class 는 자바의 지엄한 규칙에 따라, static 멤버, static 생성자, 인터페이스 등등을 선언할 수 없다.
따라서 위에서 문제를 해결하는 방법은
Solution 클래스를 static 하게 만들어 inner class 가 아니게 만드는 것이다.
그리고 실행을 해보면
오류가 발생하지 않는 것을 알 수 있다.
JAVA의 세계는 알면 알수록 무궁무진하다..
한가지 남은 궁금증은 왜 해당 코드가 잘 작동되다가, 이번에 오류가 발생되었는가 이다.
특이점이 있다면 sdk 를 java11로 바꿔서 실행해본 코드라는 것인데, 좀더 알아봐야겠다.
'개발 > 자바,스프링' 카테고리의 다른 글
커넥션 풀이란? (1) | 2025.06.19 |
---|---|
springboot querydsl 적용하기 (2) | 2025.06.13 |
Spring의 Dependency Injection(의존성 주입)과 방법론 (0) | 2025.04.24 |
window에 자바 11 설치기 (1) | 2023.09.24 |