본문 바로가기

국비교육/국비교육 복습

Day10_oop.setter2 : setter의 활용 (★)

(Q) 다음 요구사항에 맞게 데이터를 객체로 구현하고 정보를 출력하세요

 

 

- 강의시간은 30시간 단위로만 구성할 수 있습니다

- 수강료는 음수가 될 수 없습니다

- 구분은 온라인과 오프라인, 혼합 셋 중 하나로 설정할 수 있습니다

 

 

 

Lecture 클래스

 

package day10_oop.setter2;

public class Lecture {

	// 멤버 필드
	String course;
	int time;
	int price;
	String type;
	
	// setter
	// 1) 강좌명
	void setCourse(String course) {
		this.course = course;
	}
	
	// 2) 시간 - 30시간 단위로 제한
	void setTime(int time) {
		if(time % 30 != 0) {
			return;
		}
		this.time = time; 		// 그렇지 않으면의 else를 쓸 필요가 없어진다
	}
	
	// 3) 가격 - 음수가 되지 않도록 제한
	void setPrice(int price) {
		if(price < 0) {
			return;
		}
		this.price = price;
	}
	
	// 4) 구분 - 온라인/오프라인/혼합
	void setType(String type) {
		switch(type) {
		case "온라인":
		case "오프라인":
		case "혼합":
			this.type = type;
		}
	}
	
	// 생성자
	Lecture(String course, int time, int price, String type){
		this.setCourse(course);
		this.setTime(time);
		this.setPrice(price);
		this.setType(type);
	}
	
	// 출력 메소드
	void print() {
		System.out.println("강좌명 : " + this.course);
		System.out.println("강의시간 : " + this.time);
		System.out.println("수강료 : " + this.price);
		System.out.println("구분 : " + this.type);
		System.out.println();
	}
}

 

- setter 메소드를 사용하여 입력에 특별한 조건을 부여할 수 있다

- switch ~ case 에서 case를 String으로도 분류할 수 있다

 

 

 

Test01

 

package day10_oop.setter2;

public class Test01 {

	public static void main(String[] args) {
		
		// 객체 생성
		Lecture a = new Lecture("자바 마스터 과정", 90, 1000000, "온라인");
		Lecture b = new Lecture("파이썬 기초", 60, 600000, "온라인");
		Lecture c = new Lecture("웹 개발자 단기완성", 120, 1200000, "오프라인");
		
		// 출력
		a.print();
		b.print();
		c.print();
	}
}