
class Main { public static void main (String[] args) { int a = 10; int b = func(a); System.out.printf("%d, %d", a, b); } public int func (int a) { a = 20; return a; } }
error: non-static method func(int) cannot be referenced from a static context
static method가 아닌 func(int)는 static context에서 참조할 수 없다.
위 코드에서 func() method에 접근할 수 없어서 나타나는 오류이다.
Java에서 method를 메모리에 할당하는 방법 구분
static heap 메모리 할당 기준 프로그램이 실행되는 순간 연산이 실행되는 순간 메모리 정리 기준
(Garbage Collection)정리 대상이 아님 Garbage Collection에 의해 수시로 정리 객체 생성 여부 객체를 생성하지 않고도 접근 가능 new연산을 통해 객체 생성
위 표를 참고하여 다음 두 가지 방법을 적용할 수 있다.
class Main { public static void main (String[] args) { int a = 10; int b = func(a); System.out.printf("%d, %d", a, b); } public static int func (int a) { // static 선언 a = 20; return a; } }
class Main { public static void main (String[] args) { Main t = new Main(); // new 연산자로 객체 생성 int a = 10; int b = t.func(a); System.out.printf("%d, %d", a, b); } public int func (int a) { a = 20; return a; } }