학교/2-2학기(Java)

[6주차] 10/7(월) 강의내용

C0MPAS 2024. 10. 7. 23:16

1. 객체 배열

1) 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()) + " ");
		}
	}

}

 

2) 객체 배열 만들기 연습

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 sc = new Scanner(System.in);
		for(int i=0; i<book.length; i++) {
			System.out.print("제목>>");
			String title = sc.nextLine();
			System.out.print("저자>>");
			String author = sc.nextLine();

			book[i] = new Book(title, author);
		}

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

}

2. 메소드 활용

- 인자전달: 자바의 메소드 호출 시 인자 전달 방식은 "값에 의한 호출(call by value)"이다.

 

1) 기본 타입의 값이 전달되는 경우

-> 건네는 값이 매개변수에 복사되어 전달된다

2) 객체가 전달되는 경우

-> 객체가 아니라, 객체의 레퍼런스 값이 전달된다

(new가 붙는 순간 실제 객체가 생성된다 - p.205)

3) 배열이 전달되는 경우

-> (배열도 레퍼런스) / 배열이 통째로 전달되는 것이 아니며, 배열에 대한 레퍼런스만 전달된다


3. 메소드 오버로딩

(생성자 오버로딩 - p.192)

 

- 메소드 오버리딩의 조건

1) 메소드 이름이 동일하여야 한다

2) 매개변수의 개수나 타입이 서로 달라야 한다

/ 메소드의 리턴 타입이나 접근 지정자는 메소드 오버로딩과 관계없다

 

오버로딩된 메소드 호출

class MethodSample{
	public int getSum(int i, int j) {
		return i+j;
	}
	public int getSum(int i, int j, int k) {
		return i+j+k;
	}
	public double getSum(double i, double j) {
		return i+j;
	}
}


public class Lecture {
	public static void main(String[]args) {
		MethodSample a = new MethodSample();
		int i = a.getSum(1,2);
		int j = a.getSum(1,2,3);
		double k = a.getSum(1.1, 2.2);

		System.out.println(i);
		System.out.println(j);
		System.out.println(k);
	}

}

4. 객체의 소멸과 가비지 컬렉션

-> System.gc(); // 가비지 컬렉션 강제 요청


5. 접근 지정자

- 패키지: 디렉터리 혹은 폴더와 같은 개념


6. 자바의 4가지 접근 지정자

-> public

-> protected

-> 디폴트

-> private

멤버에 접근하는 클래스 멤버의 접근 지정자
private 디폴트 접근 지정 protected public
같은 패키지의 클래스 X O O O
다른 패키지의 클래스 X X X O
접근 가능 영역 클래스 내 동일 패키지 내 동일 패키지와
자식 클래스
모든 클래스
class Sample{
	public int a;
	private int b;
	int c;
}


public class AccessEx {
	public static void main(String[] args) {
		Sample sample = new Sample();
		sample.a = 10;
		//sample.b = 10;
		sample.c = 10;
	}

}

출처: 명품 JAVA Programming(개정 5판), 생능출판사