본문 바로가기

코딩공부일지/수업 review

자바 - 객체지향프로그래밍2( 오버로딩, 객체배열)

1. 오버로딩 (메서드 오버로딩)

 

 

 - "하나의 클래스 내에" 동일한 이름을 가진 메소드 중복정의
 - 같은 이름을 가진 메소드는 매개변수의 개수, 순서, 종류 중 하나가 달라야함
    (매개변수 개수가 다르거나, 반환형 순서가다르거나, 반환형이 다를시 구분 가능함)
    단, 매개변수명, 접근제한자, 반환타입은 메서드 오버로딩에 영향을 주지 않는다

public void test() {
		System.out.println("좋은아침입니다");
		System.out.println("오늘은 객체지향2 시간입니다.");
	}
	public void test(int a) {                               // 1) int 
		System.out.println("int형 매개변수 1개");
	}
	public void test(int a, String s) {                     //  2) int, String 
		System.out.println("int형 매개변수, String형 매개변수 각 1개");
	}
	
	public void test(String s, int a) {						// 3) String, int 
		System.out.println("String형 매개변수, int형 매개변수 각 1개");
	}
	public void test(int a, int b) {    					// 4) int, int 
		System.out.println("int형 매개변수 2개");
	}
//	public void test(int a, int b) {					 //     int, int => 4번과 겹침
//		System.out.println("int형 매개변수 2개");
//	}  정수형 2개를 받는test메서드를 하나 더 만들 경우, 매개변수 이름과는 관계없이 에러가 발생함
//     즉, 매개변수 자료형 개수 순서가 항상 달라야함
	
	public void test(int a, int b, String c) {           // 5) int, int, String  
	}
//	public int test(int a, int b, String c) {            // int, int, String => 5번과 겹침
//	}  반환타입이 다른것과는 관계없음. 중요한 것은 매개변수!

//	private void test(int a, int b, String c) {          // int, int, String => 5번과 겹침
//	}  접근제한자가 다른것과도 관계없음. 중요한 것은 매개변수!

	
}


public class Run {

	public static void main(String[] args) {
    OverloadingTest ot = new OverloadingTest();
	
		 // 메서드 호출부에서 호출하는 매개변수의 데이터타입의 순서, 개수에 따라 해당하는 메서드 호출
		ot.test();                 
        ot.test(1);
		ot.test(2,"가");
		ot.test("나",4);
		ot.test(5,6);

 

2. 객체배열

 

1) 객체배열의 선언 및 할당방법

[1] 객체배열의 선언
클래스명 [ ] 배열이름 = new 클래스명[배열의길이];
Animal[ ] an = new Animal [5] ; 
// Animal타입의 an 배열을 생성하여 an에 저장, an배열의 길이는 3칸

[2] 객체배열의 할당
an[0] = new Animal();
an[1] = new Animal();
an[2] = new Animal();
an[3] = new Animal();
an[4] = new Animal();
==> for문 사용가능
for (int i =0; i < length.an ; i++) {
     an[i] = new Animal();
}

예제

// 도서 정보를 입력받아서 도서들의 정보를 출력해주는 프로그램
// 책 3권의 정보를 입력받는다고 가정할 것 

// 사용자로부터 검색할 도서의 제목을 입력받아서
// 각 전체 도서들의 제목과 하나하나 비교해서 일치하는 가격을 알려주는 프로그램

public class Book {
	
	// 필드부
	private String title;
	private String publisher;
	private String author;
	private int price;
	private double discountRate;
	
	// 생성자부 --- 생성자 오버로딩
	// 모든 클래스는 반드시 하나 이상의 생성자를 가진다
	public Book () {}
	public Book (String title, String publisher, String author) {
		this.title = title;
		this.publisher = publisher;
		this.author = author;
	}
	public Book (String title, String publisher, String author, int price, double discountRate) {
		this.title = title;
		this.publisher = publisher;
		this.author = author;
		this.price = price;
		this.discountRate = discountRate;
		
	// 인스턴스변수에 매개변수 값을 대입해주지 않으면 메서드부에서 객체생성과 동시에 초기화가 되지 않음! 대입하는것 잊지마

	}
public class BookRunForReview {

	
	public static void main(String[] args) {
		
		 Book[]  bArr = new Book[3];                         // Book타입의 배열 3개 생성 ( bArr[0], bArr[1], bArr[2] ==> 배열의 값은 null 인 상태)

		 for (int i = 0; i< bArr.length; i++) {
		 Scanner sc = new Scanner(System.in);
		 System.out.println("도서의 이름: ");
		 String title = sc.next();
		 System.out.println("출판사 이름: ");
		 String publisher = sc.next();
		 System.out.println("저자: ");
		 String author = sc.next();
		 System.out.println("가격: ");
		 int price = sc.nextInt();
		 System.out.println("할인율: ");
		 double discountRate = sc.nextDouble();
		 
			 
		 bArr[i]= new Book (title, publisher, author, price, discountRate);	// bArr의 각 인덱스에 객체 연결해주기 => 객체생성과 동시에 초기화 진행
		 System.out.println(bArr[i].information());   // bArr의 각 인덱스와 연결된 객체의 information메소드 호출 
		 }
		
		 // 책 3권정보 입력받기 완료
		 
		 System.out.println("가격을 알고 싶은 책 이름을 입력하세요");
		 Scanner sc2 = new Scanner(System.in);
		 String searchPrice = sc2.next();
		 
		 for (int i=0; i < bArr.length ; i++) {
		 if ( searchPrice.equals( bArr[i].getTitle() ) ) {
			 System.out.println("입력한 책의 가격은 "+bArr[i].getPrice()+"원 입니다");
		 }
		 }
		

	}		

}