앞서 생성한 Book이라는 클래스를 이용해서 도서를 입력한 후 출력하는 프로그램을 만들었다
public class RunLibrary {
public RunLibrary() {
boolean mRoop = true;
String selected = null;
Book[] book = null; //Book이라는 클래스의 인스턴스를 담을 수 있는 배열을 생성
while(mRoop) {
System.out.print("도서입력을 진행하시겠습니까?(y/n)");
selected = input();
if(selected.equals("y")|| selected.equals("Y")) {
System.out.print("몇 권의 책을 입력하시겠습니까? : ");
int insertBook = Integer.parseInt(input());
book = new Book[insertBook];
for(int i =0; i<book.length;i++) {
output((i+1)+"번째 도서정보 입력");
output("제목 : ");
String bookName = input();
output("출판사 : ");
String bookPublishing = input();
output("출판일 : ");
String bookDate = input();
output("저자 : ");
String bookWriter = input();
output("");
book[i] = new Book(bookName,bookPublishing,bookDate,bookWriter);
}
output(book);
}
else if(selected.equals("n")|| selected.equals("N")) {
mRoop = false;
}
else {
System.out.println("<입력오류!>");
}
}
}
public static String input() {
Scanner sc = new Scanner(System.in);
return sc.nextLine();
}
public static void output(String str) {
System.out.println(str);
}
public static void output(Book[] book) { //output메서드 오버로드
for(int i =0;i<book.length;i++ ) {
output((i+1)+". 도서정보");
output("제목 : "+book[i].getName());
output("출판사 : "+book[i].getPublishing());
output("출판일 : "+book[i].getDate());
output("저자 : "+book[i].getWriter());
}
}
public static void main(String[] args) {
new RunLibrary();
}
}
이렇게 작성을 마쳤다.
그리고 동적할당과 정적할당에 대해서 배웠는데
우선 정적할당은
Car[] car = new Car[10];
위의 코드와 같이 메모리의 크기를 미리 정해놓고 할당하는 것으로 메모리의 크기가 변하지 않고 Stack의 영역에 저장이 된다.
그리고 동적할당은
int array = 10;
Car [] car = new Car[array];
메모리의 크기를 정해 놓지 않고 프로그램이 실행되는 중에 메모리의 크기를 할당하는 것 인데
위의 코드를 보면 array에 10이 초기화 됐고 그러면 [array]에 10이 들어가니까 정적할당이 아닌가? 라고
생각할 수도 있지만 컴파일 시점에는 int array에는 10이 초기화 되지만
[array]에는 10이 들어가지 않고 run time 즉, 프로그램이 실행중일때 [array]에 10이란 값이 들어가기 때문에
정적할당이 아닌 동적할당으로 볼 수가 있다.
정리를 하자면
정적할당 : 메모리의 크기를 정해놓고 할당하여 크기가 변하지 않고 컴파일시점에 Stack에 쌓이는 것
동적할당 : 메모리의 크기를 정해놓지 않고 run time 중에 메모리의 크기를 할당하는 것(Heap영역)
이라고 볼 수 있다.
'JAVA' 카테고리의 다른 글
for 문 (0) | 2021.06.03 |
---|---|
클래스 3 (0) | 2021.05.14 |
클래스 1(Class,object,instance) (0) | 2021.05.14 |
method (0) | 2021.05.14 |