- 객체배열
- 객체를 저장하는 배열로 배열의 자료형을 클래스명(사용자 정의 자료형)으로 지정하여 활용
- 객체배열 선언과 할당
- 선언
- 클래스명[] 배열명;
- 클래스먕 배열명[];
- 할당
- 배열명 = new 클래스명[배열크기];
- 선언과 동시에 할당
- 클래스명 배열명[] = new 클래스명[배열크기];
- 선언
- 객체배열 초기화
- 인덱스를 이용한 초기화
- 배열명[i] = new 클래스명();
- 선언과 동시에 할당 및 초기화
- 클래스명 배열명[] = {new 클래스명(),new 클래스명()};
- 주소값이 저장 -> 해당 클래스의 객체를 가리킴
- 객체 -> 다른 타입의 자료형들이 묶여있음 방의 크기가 다 다름
- 인덱스를 이용한 초기화
* 객체배열 실습
package com.test01.model;
public class Book {
//필드
private String title;
private String writer;
private String publisher;
private int price;
//생성자(기본, 매개변수)
public Book() {}
public Book(String title, String writer, String publisher, int price) {
this.title = title;
this.writer = writer;
this.publisher = publisher;
this.price = price;
}
//getter&setter
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getWritter() {
return this.writer;
}
public void setWritter(String writer) {
this.writer = writer;
}
public String getPublisher() {
return this.publisher;
}
public void Setpublisher(String publisher) {
this.publisher = publisher;
}
public int getPrice() {
return this.price;
}
public void SetPrice(int price) {
this.price = price;
}
public String information() {
return "title=" + title+", writer="+writer+", publisher="+publisher+", price="+price;
}
}
package com.test01.run;
import java.util.Scanner;
import javax.imageio.plugins.tiff.GeoTIFFTagSet;
import com.test01.model.Book;
public class ObjectArrayTest {
public static void main(String[] args) {
//선언 및 할당
//Book[] bk = new Book[3];
//초기화
//bk[0] = new Book();
//bk[1] = new Book();
//bk[2] = new Book();
//선언 및 할당과 동시에 초기화까지
Book[] bk = { new Book("자바의 정석","홍길동","한빛",20000),
new Book("이것이 자바다", "신용권", "한빛", 30000),
new Book("이것이 mysql이다", "이창진","멀티",40000)};
System.out.println(bk); //배열의 주소
System.out.println(bk[0]); //Book클래스 객체의 주소
System.out.println(bk[0].getPrice()); //필드 price의 값
System.out.println();
//도서 출력
for(int i=0; i<bk.length; i++) {
System.out.println(bk[i].information());
}
//도서 검색
//제목 입력 받아 저장된 book 객체의 title값과 동일하면 information 실행
Scanner sc = new Scanner(System.in);
System.out.print("검색할 책 제목 : ");
String searchTitleString = sc.nextLine();
for(int i=0; i<bk.length; i++) {
if(bk[i].getTitle().equals(searchTitleString)) {
System.out.println(bk[i].information());
break;
}
}
}
}
'JAVA' 카테고리의 다른 글
[JAVA #8] 9. 다형성(Polymorphism) (1) | 2023.03.02 |
---|---|
[JAVA #7] 8. 상속(Inherit) (0) | 2023.02.28 |
[JAVA #6] 6. 객체 (0) | 2023.02.27 |
[JAVA 실습 #5] 5. 2차원 배열 (0) | 2023.02.26 |
[JAVA 실습 #5] 4. 배열(Array) (0) | 2023.02.25 |