본문 바로가기
학교/2-2학기(Java)

[5주차] 10/2(수) 강의내용

by C0MPAS 2024. 10. 2.

1. this 레퍼런스

-> this의 필요성

class Circle{
	int radius;
	String name;
    
	double getArea() {
		return 3.14 * radius * radius;
	}

	Circle(){
		radius = 1;
		name = "";
	}

	Circle(int r, String s){
		radius = r;
		name = s;
	}

	Circle(int radius){
    		//this.radius = radius;
		radius = radius;
	}
}


public class Lecture {
	public static void main(String[] args) {
		Circle pizza;
		pizza = new Circle(5);
		System.out.println("피자의 면적은 " + pizza.getArea());
	}

}

 

// 예제4-4

public class Book {
	String title;
	String author;
    
	// 생성자 Book을 추가해서 Book abc = new Book() 실행가능하도록
	public Book() {
	}

	public Book(String t) {
		title = t;
		author = "작자미상";
	}

	public Book(String t, String a) {
		title = t;
		author = a;
	}

	public static void main(String[] args) {
		Book littlePrince = new Book("어린왕자", "생텍쥐페리");
		Book loveStory = new Book("춘향전");
		Book abc = new Book(); // 추가
        
		System.out.println(littlePrince.title + " " + littlePrince.author);
		System.out.println(loveStory.title + " " + loveStory.author);
		System.out.println(abc.title + " " + abc.author); // 추가
	}

}

 


2. this( )로 다른 생성자 호출

public class Book {
	String title;
	String author;

	void show() {
		System.out.println(title + " " + author);
	}

	public Book() {
		this("",""); // title과 author 둘 다 있는 경우의 생성자를 부르게 되는 것
		System.out.println("생성자 호출됨");
	}

	public Book(String title) {
		this(title, "작자미상");
	}

	public Book(String title, String author) {
		this.title = title;
		this.author = author;
	}	

	public static void main(String[] args) {
		Book littlePrince = new Book("어린왕자", "생텍쥐페리");
		Book loveStory = new Book("춘향전");
		Book emptyBook = new Book();
		loveStory.show();
	}

}

3. this() 사용 시 주의할 점

1) this()는 반드시 생성자 코드에서만 호출할 수 있다

2) this()는 반드시 같은 클래스 내 다른 생성자를 호출할 때 사용된다

3) this()는 반드시 생성자의 첫 번째 문장이 되어야 한다


4. 객체 치환 시 주의할 점

-> 가비지 컬렉션

public class Circle {
	int radius;

	public Circle(int radius) { this.radius = radius; }
	public void set(int radius) { this.radius = radius; }
	
	public static void main(String args[]) {
		Circle ob1 = new Circle(1);
		Circle ob2 = new Circle(2);
		Circle s;
		
		s = ob2;
		ob1 = ob2;
		System.out.println("ob1.radius=" + ob1.radius);
		System.out.println("ob2.radius=" + ob2.radius);
	}
	
}

5. 객체 배열

배열 선언 및 생성

배열의 원소 객체 접근

예제 4-6

예제 4-7


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

'학교 > 2-2학기(Java)' 카테고리의 다른 글

[7주차] 10/14(월) 강의내용  (0) 2024.10.14
[6주차] 10/7(월) 강의내용  (0) 2024.10.07
[5주차] 9/30(월) 강의내용  (0) 2024.09.30
[4주차] 9/25(수) 강의내용  (1) 2024.09.25
[4주차] 9/23(월) 강의내용  (0) 2024.09.23

댓글