티스토리 뷰



에러 내용


error: non-static method test() cannot be referenced from a static context


static 메소드가 아닌 test() 메소드는 static context 안에서 참조될 수 없다.






원인


아래 코드를 보자

1
2
3
4
5
6
7
8
9
10
public class hello {
        public static void main(String[] args) {
                test();
        }
 
        public void test() {
            System.out.println("test");
        }
}

cs


static 인 main 메소드 안에 non-static 인 test 메소드가 들어가있다.

실행시켜보면 아래와 같은 에러를 뿜뿜한다.


1
2
3
4
5
iyeong-uui-MacBook-Pro:test meongchong-ja$ javac hello.java
hello.java:9: error: non-static method test() cannot be referenced from a static context
        test();
        ^
1 error
cs






해결 방법


두 가지 방법이 있다.


1. test() 메소드를 static 으로 선언하는 방법


1
2
3
4
5
6
7
8
9
public class hello {
        public static void main(String[] args) {
                test();
        }
 
        public static void test() {
            System.out.println("test");
        }
}
cs



2. hello class의 객체를 생성하는 방법


1
2
3
4
5
6
7
8
9
10
public class hello {
        public static void main(String[] args) {
                hello h = new hello();
                h.test();
        }
 
        public void test() {
            System.out.println("test");
        }
}
cs











공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함