package ch08;
public class Bus {
int busNumber; //본인 버스번호
int count; // 승객 수
int money; //수익금
// 생성자
public Bus(int number) {
busNumber = number;
}
//승객을 태우다
//행위는 멤버 변수와 관련이 많다!
public void take(int pay) {
money += pay;
count++;
}
public void showInfo() {
System.out.println("==== 상태창 ====");
System.out.println("버스 번호 : " + busNumber);
System.out.println("버스 승객 수 : " + count);
System.out.println("버스 수익금 : " + money);
}
}
package ch08;
public class Student {
String name;
int money;
public Student(String n, int m) {
name = n;
money = m;
}
//버스를 탄다
public void takeBus(Bus bus) {
//bus.take(1000);
//학생 소지금 1000원을 빼 준다
//money -= 1000;
//money -= 1000; // money = money - 1000;
if (money < 1000) {
System.out.println("요금이 부족합니다");
} else {
bus.take(1000);
money -= 1000;
}
}
//지하철을 탄다
public void takeSubway(Subway subway) {
if (money < 1500) {
System.out.println("요금이 부족합니다");
} else {
subway.take(1500);
money -= 1500;
}
}
public void showInfo() {
System.out.println("==== 상태창 ====");
System.out.println("학생 이름 : " + name);
System.out.println("소지금 : " + money);
}
}
package ch08;
public class Subway {
int lineNumber; //호선
int count; //승객 수
int money; //요금
//생성자
public Subway(int number) {
lineNumber = number;
}
public void take(int pay) {
money += pay;
count++;
}
public void showInfo() {
System.out.println("==== 상태창 ====");
System.out.println("지하철 호선 : " + lineNumber);
System.out.println("지하철 승객 수 : " + count);
System.out.println("지하철 수익금 : " + money);
}
}
(코드를 실행시키는 코드)
package ch08;
public class GoingToSchool {
public static void main(String[] args) {
Bus b100 = new Bus(100);
//Bus b200 = new Bus(200);
Subway s1호선 = new Subway(1);
//Subway s2호선 = new Subway(2);
Student studentKim = new Student("철수", 1000);
//Student studentLee = new Student("성호", 3000);
Student studentChoi = new Student("원종", 10000);
//Student studentJean = new Student("수연", 5000);
System.out.println("-----------------------------------------");
//실습
//1. 학생에게 지하철 타는 기능도 만들어보기 (상호작용)
//2. 응용 (방어적 코드 작성 - 소지금이 업슬 경우 등)
studentKim.takeBus(b100); //김철수가 버스를 탄다
//studentLee.takeBus(b200); //이성호가 버스를 탄다
studentChoi.takeSubway(s1호선); //최원종이 지하철을 탄다
//studentJean.takeSubway(s2호선); //진수연이 지하철을 탄다
studentKim.showInfo();
// studentLee.showInfo();
studentChoi.showInfo();
//studentJean.showInfo();
b100.showInfo();
//b200.showInfo();
s1호선.showInfo();
//s2호선.showInfo();
}
}