본문 바로가기

Language/JAVA

[JAVA] 명품 자바 에센셜 예제 4장

 

예제 4 - 1: Circle 클래스의 객체 생성 및 활용
문제: 반지름과 이름을 가진 Circle 클래스를 작성하고, Circle 클래스의 객체를 생성하라.

package chap04;

public class Circle {

	int radius;
	String name;
	
	public Circle() {
		radius=1; name="";
	}
	
	public Circle(int r, String n) {
		radius=r; name=n;
	}
	
	public double getArea() {
		return 3.14*radius*radius;
	}
	
	public static void main(String[] args) {
		Circle pizza=new Circle(10,"자바피자");
		double area=pizza.getArea();
		System.out.println(pizza.name+"의 면적은 "+area);
		
		Circle donut=new Circle();
		donut.name="도넛피자";
		area=donut.getArea();
		System.out.println(donut.name+"의 면적은 "+area);
	}

}
//출력결과
자바피자의 면적은 314.0
자바도넛의 면적은 12.56

 

예제 4-2 : Rectangle 클래스 만들기 연습
문제: 너비(width)와 높이(height) 필드, 그리고 면적 값을 제공하는 getArea() 메소드를 가진 Rectangle 클래스를 작성하라.

package chap04;
//예제 4-2
import java.util.Scanner;


class Rectangle {
	 int width;
	 int height;
	 public int getArea() {
		 return width*height;
	 }
}

public class RectApp{
	public static void main(String[] args) {
		Rectangle rect=new Rectangle();
		Scanner scanner=new Scanner(System.in);
		System.out.println(">>");
		rect.width=scanner.nextInt();
		rect.height=scanner.nextInt();
		System.out.println("사각형의 면적은 "+rect.getArea());
		scanner.close();
	}
}
//출력결과
>>4 5
사각형의 면적은 20

 

예제 4-3 : 두 개의 생성자를 가진 Circle 클래스
문제: 두 개의 생성자를 가진 Circle 클래스를 만들어 보라.

package chap04;

public class Circle {

	int radius;
	String name;
	
	public Circle() {
		radius=1; name="";
	}
	
	public Circle(int r, String n) {
		radius=r; name=n;
	}
	
	public double getArea() {
		return 3.14*radius*radius;
	}
	
	public static void main(String[] args) {
		Circle pizza=new Circle(10,"자바피자");
		double area=pizza.getArea();
		System.out.println(pizza.name+"의 면적은 "+area);
		
		Circle donut=new Circle();
		donut.name="도넛피자";
		area=donut.getArea();
		System.out.println(donut.name+"의 면적은 "+area);
	}

}
//출력결과
자바피자의 면적은 314.0
도넛피자의 면적은 3.14

 

예제 4-4 : 생성자 선언 및 호출 연습
문제: 제목과 저자를 나타내는 title과 author필드를 가진 Book 클래스를 작성하고, 생성자를 작성하여 필드를 초기화하라.

package chap04;

public class Book {
	String title;
	String author;
	
	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("춘향전");
		System.out.println(littlePrince.title+" "+ littlePrince.author);
		System.out.println(loveStory.title+" "+loveStory.author);
	}

}
//출력결과
어린왕자 생텍쥐페리
춘향전 작자미상

 

예제 4-5 : this()로 다른 생성자 호출
문제: 예제 4-4에서 작성한 Book 클래스의 생성자를 this()를 이용하여 수정하라.

package chap04;

public class Book4_5 {

	String title;
	String author;
	void show() {
		System.out.println(title+" "+author);
	}
	
	public Book4_5() {
		this("","");
		System.out.println("생성자 호출됨");
	}
	
	public Book4_5(String title) {
		this(title, "작자미상");
	}
	
	public Book4_5(String title, String author) {
		this.title=title;
		this.author=author;
	}
	public static void main(String[] args) {
		Book4_5 littlePrince=new Book4_5("어린왕자","생텍쥐페리");
		Book4_5 loveStory=new Book4_5("춘향전");
		Book4_5 emptyBook=new Book4_5();
		loveStory.show();
	}

}
//출력결과
생성자 호출됨
춘향전 작자미상

 

예제 4-6 : Circle 배열 만들기
문제:Circle 객체 5 개를 가지는 배열을 생성하고 , Circle 객체의 반지름을 0 에서 4 까지 각각 지정한 후 , 면적을 출력하라.

package chap04;

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

public class CircleArray {

	public static void main(String[] args) {
		Circle4_6[] c;
		c=new Circle4_6[5];
		
		for(int i=0;i<c.length;i++) {
			c[i]=new Circle4_6(i);
		}
		for(int i=0;i<c.length;i++) {
			System.out.print((int)(c[i].getArea())+" ");
		}
	}

}
//출력결과
0 3 12 28 50

 

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

package chap04;

import java.util.Scanner;

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


public class BookArray {
	public static void main(String[] args) {
		Book4_7[] book=new Book4_7[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 Book4_7(title,author);
			
		}
		for(int i=0; i<book.length;i++) {
			System.out.print("("+book[i].title+","+book[i].author+")");
		}
		
		scanner.close();
	}

}
//출력결과
제목>>사랑의 기술
저자>>에리히 프롬
제목>>시간의 역사
저자>>스티븐 호킹
(사랑의 기술, 에리히 프롬)(시간의 역사, 스티븐 호킹)

 

예제 4-8 : 인자로 배열이 전달되는 예
문제: char[] 배열을 전달받아 배열 속의 공백 (' ') 문자를 로 대치하는 메소드를 작성하라.

package chap04;

public class ArrayParameter {

	static void replaceSpace(char a[]) {
		for(int i=0; i<a.length;i++) {
			if(a[i]==' ') {
				a[i]=',';
			}
		}
	}
	
	static void printCharArray(char a[]) {
		for(int i=0; i<a.length;i++) {
			System.out.print(a[i]);
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		char c[]= {'T','h','i','s',' ','i','s',' ','a',' ','p','e','n','c','i','l'};
		printCharArray(c);
		replaceSpace(c);
		printCharArray(c);
	}

}
//출력결과
This is a pencil.
This,is,a,pencil

 

예제 4-9  : 가비지의 발생
문제:다음 소스에서 언제 가비지가 발생하는지 설명하라.

예제 4-10 : 멤버의 접근 지정자
문제: 다음 코드의 두 클래스 Sample 과 AccessEx 클래스는 동일한 패키지에 저장된다. 컴파일 오류를 찾아 내고 이유를 설명하라.

예제 4-11 : static 멤버를 가진 Calc 클래스 작성
문제: 전역 함수로 작성하고자 하는 abs, max, min 의 3 개 함수를 static 메소드를 작성하고 호출하는 사례를 보여라.