객체 배열


  • 객체를 원소로 갖는 객체 배열이다.
  • 객체를 원소로 갖는 객체 배열이라는 말은, 객체 레퍼런스를 원소로 갖는 배열이다.

객체 배열을 만들기 위해 다음과 같은 단계로 진행된다.

객체에 대한 레퍼런스 선언 -> 레퍼런스 배열 생성 -> 객체 생성



Circle [] c; // Circle 클래스의 배열에 대한 레퍼런스 변수 c를 선언한다.
c = new Circle[5]; // Circle 객체에 대한 레퍼런스 5개를 생성한다.
for(int i=0; i<c.length; i++) 
    c[i] = new Circle(i); // i 번째 Circle 객체 생성

for(int i=0; i<c.length; i++)
    System.out.print((int)(c[i].getArea()) + " "); //배열 c의 i번째 객체에 접근하기 위해서 c[i]레퍼런스를 사용한다.

예시


반지름이 0~4인 Circle 객체 5개를 가지는 배열을 생성하고, 배열에 있는 모든 Circle 객체의 면적을 출력하라.


class Circle{
    int radius;
    public Circle(int radius) {
        this.radius = radius;
    }
    public double getArea() {
        return 3.14*radius*radius;
    }
}

public class CircleArray {
    public static void main(String[] args) {
        Circle [] c;
        c = new Circle[5];

        for(int i=0; i<c.length; i++) {
            c[i] = new Circle(i);
        }

        for(int i=0; i<c.length; i++) {
            System.out.print((int)c[i].getArea()+" ");
        }
    }
}

실행결과
0 3 12 28 50 

예시


예제 4-4의 Book 클래스를 활용하여 2개짜리 Book 객체 배열을 만들고, 사용자로부터 책의 제목과 저자를 입력받아 배열을 완성하라.


import java.util.Scanner;
class Book{
    String title,author;
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
}
public class BookArray {
    public static void main(String[] args) {
        Book [] book = new Book[2];

        Scanner scanner = new Scanner(System.in);
        for(int i=0; i<book.length; i++) {
            System.out.print("제목>>");
            String title = scanner.nextLine();
            System.out.print("저자>>");
            String author = scanner.nextLine();
            book[i] = new Book(title, author);
        }

        for(int i=0; i<book.length; i++) {
            System.out.print("(" + book[i].title+", "+book[i].author + ")");

        }
        scanner.close();
    }
}

실행결과
제목>>캠잰슨
저자>>데이비드아들러
제목>>씨플프로그래밍
저자>>황기태
(캠잰슨, 데이비드아들러)(씨플프로그래밍, 황기태)

+ Recent posts