질문
여기에서 plus() 메소드가 빨간색이 나오는데
이해가 잘 가지 않습니다.
제 생각에는 될것 같습니다만 이유가 무엇일까요?
구글에 뭐라고 검색하면 될까요?
답변
이유
static 키워드가 붙으면 JVM이 제일 먼저 메모리를 할당해줍니다.
static 키워드가 붙지 않은 method를 static method에서 호출하려고 하면 컴파일 오류가 납니다. 그 이유는 static method는 이미 JVM이 먼저 메모리를 할당해줬는데 호출하려는 method는 메모리에 올라가 있지 않기 때문입니다. 즉, static method 안에서는 메모리에 올라가는 시점이 동일한 static method만 사용할 수 있습니다.
따라서 plus()를 호출하고 싶다면 UserDao 클래스를 main method에서 인스턴스화 한 다음 진행해야 합니다.
public class UserDao {
public void plus(int first, int second) {
System.out.println(first + second);
}
public static void main(String args[]) {
UserDao userDao = new UserDao(); //UserDao 클래스 인스턴스화
userDao.plus(10, 20); //userDao를 통해 호출
}
}
Java
복사
static 키워드 없이 인스턴스화 후 plus() 호출
질문하신 것처럼 plus()를 호출하려면 아래와 같이 static 키워드를 붙이면 됩니다.
public class UserDao {
public static void plus(int first, int second) { //static method
System.out.println(first + second);
}
public static void main(String args[]) {
plus(10, 20); //static method 안에서 static method 호출
}
}
Java
복사
static method 안에서 static method 호출
구글링 키워드
static JVM 메모리 할당