Java 전역변수 지역변수 질문좀드리겠습니다
조회수 667회
Adapter test; //인스턴스변수
public void Test(){
ArrayList<String> items = new ArrayList<>();
test = new Adapter(items);
}
메소드 안에 items 는 지역변수이고
인스턴스변수 test 는 메소드안에서 new Adapter(itmes); 할당을받는데
test는 인스턴수변수이고 items 는 지역변수인데
메소드가끝나면 items 는 지역변수니까 메모리가 해제되면
인스턴스 변수인 test 에 파라메터로 넘겨준 items 의 메모리는 그냥 사라지는건가요?
제 생각은 어쨌든 new ArrayList<>();로 할당받았기때문에 메모리 주소는 남아있을거같은데..
궁금합니다!!
Adapter 는 임의의 Adapter 입니다
1 답변
-
Test()
메서드가 종료되었다고 해서 인스턴스 멤버에 할당된 인스턴스가 바로 사라지지는 않습니다. 다른곳에서 참조를 할 수 있으니까요.package misc; import java.util.ArrayList; public class TryEverything { public static void main(String[] args) { LifeCycle lc = new LifeCycle(); lc.Test(); System.out.println(lc.getTest()); // misc.Adapter@22555ebf } } class LifeCycle { private Adapter test; // 인스턴스변수 public Adapter getTest() { return test; } public void Test() { ArrayList<String> items = new ArrayList<>(); test = new Adapter(items); } } class Adapter { private ArrayList<String> items; public Adapter(ArrayList<String> items) { this.items = items; } }
댓글 입력