프로그래밍 언어/Java
09. [Java] 객체 간 협력
물꼮이
2022. 1. 31. 23:14
Student 학생의 객체가,
Bus, Subway 두개의 객체와 상호작용하며,
이를 TakeTrans 클래스의 main 함수로 사용하는 과정을 예제로 표현한 것이다.
1. Student
package cooperation;
public class Student {
public String studentName; // 학생 이름
public int grade; // 학년
public int money; // 학생이 가지고 있는 돈
// 생성자
public Student(String studentName, int money) // 이름과 돈 초기화하기
{
this.studentName = studentName;
this.money = money;
}
// 메서드1
public void takeBus(Bus bus) { // Bus 클래스를 자료형으로 함
bus.take(1000);
this.money -= 1000;
}
// 메서드2
public void takeSubway(Subway subway) { // Subway 클래스를 자료형으로 함
subway.take(1500);
this.money -= 1500;
}
// 메서드3
public void showInfo() {
System.out.println(studentName + "님의 남은 돈은 " + money + "입니다.");
}
}
2. Bus
package cooperation;
public class Bus {
int busNumber; // 버스 번호
int passengerCount; // 승객 수
int money; // 버스의 수입
// 생성자
public Bus(int busNumebr) // 버스 번호를 매개변수로 받는 생성자
{
this.busNumber = busNumebr;
}
// 메서드1
public void take(int money) // 승객이 낸 돈을 받음
{
this.money += money; // 버스의 수입 증가
passengerCount++; // 승객 수 증가
}
// 메서드2
public void showInfo() { // 버스 정보를 출력하는 함수
System.out.println("버스 " + busNumber + "번의 승객은 " + passengerCount +"명이고, 수입은 " + money + "입니다.");
}
}
3. Subway
package cooperation;
public class Subway {
String lineNumber; // 지하철 노선 번호
int passengerCount; // 승객 수
int money; // 수입 액
// 생성자
public Subway(String lineNumber) { // 지하철 노선 초기화
this.lineNumber = lineNumber;
}
// 메서드1
public void take(int money) { // 승객이 탄 경우
this.money += money; // 수입 증가
passengerCount++; // 승객 수 증가
}
// 메서드2
public void showInfo() // 지하철 정보 출력
{
System.out.println(lineNumber + "의 승객은 " + passengerCount +"명이고, 수입은 " + money + "입니다.");
}
}
4. TakeTrans
package cooperation;
public class TakeTrans {
public static void main(String[] args) {
// 두 명의 학생을 생성
Student studentJames = new Student("James", 5000);
Student studentTomas = new Student("Tomas", 10000);
Bus bus100 = new Bus(100); // Bus 클래스의 인스턴스 생성 후 사용!!
studentJames.takeBus(bus100); // james가 100번 버스를 탐
studentJames.showInfo(); // james 정보 출력
bus100.showInfo(); // 버스 정보 출력
Subway subwayGreen = new Subway("2호선");
studentTomas.takeSubway(subwayGreen); // Tomas가 2호선을 탐
studentTomas.showInfo(); // Tomas 정보 출력
subwayGreen.showInfo();
}
}