class Books{

 String title;

 String author;

}

public class BooksTestDrive {

 public static void main(String args[]){

  Books [] myBooks = new Books[3];

  //myBooks[0]  = new Books();

  //myBooks[1]  = new Books();

  //myBooks[2]  = new Books();

  int x = 0;

  myBooks[0].title = "The Grapes of JAVA";

  myBooks[1].title = "The JAVA of Gatsby";

  myBooks[2].title = "The JAVA Cook Books";

  myBooks[0].author = "bob";

  myBooks[1].author = "sue";

  myBooks[2].author = "ian";

  

  while (x < 3){

   System.out.println(myBooks[x].title);

   System.out.println(" by ");

   System.out.println(myBooks[x].author);

   x = x + 1;

  }

  

 }


}


굵게 글씨쓴 부분이 존재하지 않으면(그니까 주석을 풀지 않는다면) 프로그램 오류가 뜬다.


이유인 즉슨,

 Books [] myBooks = new Books[3]; 이 구문은 단순히 배열만 선언 했다는것!

지금은 Books 배열에 들어있는 원소는 Books 레퍼런스 변수에 불과하다는 점이다!


Books 객체는 따로 만들어 주어야 한다.

'Programing > JAVA' 카테고리의 다른 글

접근 한정자 예제(객체지향 예제)  (0) 2015.02.10
인스턴스 복사  (0) 2015.02.10
Setter와 Getter  (0) 2015.02.10
다형성 배열을 이용하여 객체를 생성!  (0) 2015.02.10
추상 클래스, 추상 메소드의 개념  (0) 2015.02.10
Posted by kimmayer

블로그 이미지
IT 기술들 정리, 독후감을 주로 남깁니다!
kimmayer

공지사항

Yesterday
Today
Total

달력

 « |  » 2024.3
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
31

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함