Java
생성자와 메서드를 활용해 class 사이 상호작용을 해본다
조충희
2025. 4. 15. 17:33
Bus, Subway
Student 클래스를 각각 작성했다.
Student가 대중교통을 이용하면 잔고가 줄고
대중교통은 잔고가 늘어나는 프로그램을 만들어본다.
먼저 Bus 클래스 설계
클래스를 설계할때는 속성 / 생성자 / 메서드 순으로 하면 된다.
package ch10;
// 클래스 설계 측
public class Bus {
int busNo; int busCount; int busincome;
// 생성자
public Bus(int bno) {
busNo = bno;
// 객체 생성시 가장 먼저 실행
}
// 메서드 - 승객을 태워보자
public void take(int pay) {
busincome += pay;
busCount ++;
}
public void ShowInfo() {
System.out.println("===== 상태창 =====");
System.out.println("버스 번호: " + busNo);
System.out.println("버스 승객수: " + busCount);
System.out.println("버스 총수익: " + busincome);
}
} // end of class
Subway 클래스 설계
package ch10;
public class Subway {
int subNo;
int subCount;
int subIncome;
public Subway(int sno) {
subNo = sno;
}
// 승객을 태우다.
public void take(int pay) {
subIncome += pay;
subCount ++;
}
// 상태창
public void ShowInfo() {
System.out.println("===== 상태창 =====");
System.out.println("지하철 번호: " + subNo);
System.out.println("지하철 승객수: " + subCount);
System.out.println("지하철 총수익: " + subIncome);
}
} // end of class
Student 클래스 설계
takeBus 메서드는 Bus 클래스에서 take 메서드를 불러오는 역할이다...
package ch10;
// 클래스 설계 측
public class Student {
String name;
int money;
// 매개변수 2개를 받는 생성자를 만들어보자
public Student(String snm, int smn) {
name = snm;
money = smn;
}
// 학생이 버스를 탄다
public void takeBus(Bus bus) {
bus.take(1000);
// 버스에 1000원을 내고 내 멤버변수 money에 -1000원
money -= 1000;
}
// 학생이 지하철을 탄다
// 학생의 상태창
public void ShowInfo() {
System.out.println("===== 상태창 =====");
System.out.println("학생이름: " + name);
System.out.println("학생소지금: " + money);
}
} // end of class
위 클래스들을 활용해 버스이용 프로그램을 만들어봤다.
package ch10;
public class GoingToSchool {
// main
public static void main(String[] args) {
Bus bus1 = new Bus(133);
Bus bus2 = new Bus(1004);
Subway sub1 = new Subway(3);
Student stu1 = new Student("홍길동", 10000);
Student stu2 = new Student("티모", 5000);
stu1.ShowInfo();
// 학생1이 버스를 탔다.
stu1.takeBus(bus1); // bus1의 실제값은 주소이다.
stu1.ShowInfo(); bus1.ShowInfo();
// 학생2가 버스를 탔다.
stu2.takeBus(bus1);
stu2.ShowInfo(); bus1.ShowInfo();
/*
기본 데이터 타입 / 참조 데이터 타입
참조타입은 대문자로 선언된다.
*/
} // end of main
} // end of class
대중교통 이용 예제2
package ch10;
public class GoingToSchool2 {
//main
public static void main(String[] args) {
//버스 객체를 3개 생성
Bus bus1 = new Bus(133);
Bus bus2 = new Bus(179);
Bus bus3 = new Bus(1004);
//학생 개체를 3개 생성
Student stu1 = new Student("홍길동", 10000);
Student stu2 = new Student("장길산", 5000);
Student stu3 = new Student("임꺽정", 2500);
//학생이 버스를 타는 행위를 구현
stu1.takeBus(bus1); stu2.takeBus(bus1); stu3.takeBus(bus2);
//버스 상태창 출력
bus1.ShowInfo(); bus2.ShowInfo(); bus3.ShowInfo();
stu1.ShowInfo(); stu2.ShowInfo(); stu3.ShowInfo();
}//end of main
}//end of class