Java & Kotlin
[Java 객체지향] 객체 간 상호작용 구현해보기
Sue
2022. 1. 26. 23:26
객체지향 프로그래밍 할 때 고려할 점
1. 무엇을 객체로 구현할 지 정해야 한다.
2. 그 객체의 역할에 따른 속성과 기능을 구현해야 한다.
3. 하나의 객체는 객체의 이름에 맞는 유일한 기능을 해야한다.
객체 간 상호작용
객체 간 상호작용을 위한 정보 전달은 메세지 전달을 통해 이루어지기도 하고, 객체 자체가 매개 변수로 전달될 수 도 있다.
예제 프로그램
1) 학생이 버스나 지하철을 타면 요금을 지불하고 버스나 지하철은 그만큼의 수익을 얻고 승객 수가 늘어난다.
Student.java
- 학생 클래스는 이름과 가지고 있는 금액을 속성으로 갖는다.
- takeBus, takeSubway는 매개 변수로 각각 Bus, Subway 클래스의 객체를 받는다.
- take 메서드를 이용해 버스와 지하철의 수입이 증가한다.
package ch14;
public class Student {
String studentName;
int money;
public Student(String studentName, int money) {
this.studentName = studentName;
this.money = money;
}
public void takeBus(Bus bus) { // 매개 변수로 Bus의 객체를 받음.
bus.take(1000);
this.money -= 1000;
}
public void takeSubway(Subway subway) { // 매개 변수로 Subway의 객체를 받음.
subway.take(1200);
this.money -= 1200;
}
public void showInfo() {
System.out.println(studentName + "님의 잔액은 " + money + "원 입니다.");
}
}
Bus.java
- 속성은 버스 번호, 승객 수, 수입.
- Student 클래스에서 사용한 take 메서드를 구현해준다.
- 버스 인스턴스의 수입이 매개변수로 들어온 수입만큼 증가하고 승객 수가 증가한다.
- Subway.class도 이와 유사
package ch14;
public class Bus {
int busNum;
int passengerCount;
int income;
public Bus(int busNum) {
this.busNum = busNum;
}
public void take(int income) { // Student 클래스에서 사용할 take 메서드 구현
this.income += income;
passengerCount++;
}
public void showBusInfo() {
System.out.println(busNum + "번 버스의 승객 수는 " + passengerCount + "명이고, 수입은 " + income + "원 입니다.");
}
}
Test.java
package ch14;
public class Test {
public static void main(String[] args) {
Student sue = new Student("Sue", 10000);
Student elie = new Student("Elie", 6000);
Bus bus100 = new Bus(100);
Subway greenSubway = new Subway(2);
sue.takeBus(bus100);
sue.showInfo();
bus100.showBusInfo();
elie.takeSubway(greenSubway);
elie.showInfo();
greenSubway.showSubwayInfo();
}
}
수행 결과
Sue님의 잔액은 9000원 입니다.
100번 버스의 승객 수는 1명 이고, 수입은 1000원 입니다.
Elie님의 잔액은 4800원 입니다.
2번 버스의 승객 수는 1명 이고, 수입은 1200원 입니다.
2) 고객은 계좌를 생성하고, 입금과 출금을 할 수 있다. 출금은 비밀번호를 필요로 하고 잔액이 부족하면 출금이 되지 않는다.
이건 수업시간에 한 건 아니고 배운 것 써먹고 싶어서 추가로 짠 프로그램이다. 원래 Account를 생성해주는 Bank 클래스도 만들고 싶었는데 아직은 잘 모르겠담,, 뭔가 디자인 패턴 중 하나 사용하면 될 것 같은데 더 배우고 나중에 다시 시도해봐야겠다!
Customer.java
원래 password 속성을 넣었었는데 그렇게 할 경우 Account의 withdrawl 메서드에서 패스워드를 비교하는 걸 구현할 수 없어서 Account의 속성에 넣었다. 클래스는 이름에 맞는 속성을 갖는 것이 중요하다는 게 와닿았음.
package bank;
public class Customer {
String name;
int balance;
public Customer(String name, int balance) {
this.name = name;
this.balance = balance;
}
}
Account.java
package bank;
public class Account {
int accountNum;
int balance = 0;
String password;
public Account(Customer customer, String password) {
this.balance = customer.balance; // 고객의 초기 금액 설정
this.password = password;
System.out.println(customer.name + "님의 계좌가 생성되었습니다.");
}
public void withdrawl(int money, String password) {
if(this.password.equals(password)) { // 매개변수로 들어온 비밀번호가 기존에 생성한 비밀번호와 일치하면 조건문 실행
if(money > balance) {
System.out.println("잔액이 부족합니다.");
}
else {
this.balance -= money;
}
}
else { // 비밀번호가 일치하지 않았을 경우 메세지 출력
System.out.println("비밀번호가 일치하지 않습니다.");
}
}
public void deposit(int money) {
this.balance += money;
}
public void showAustomerInfo(Customer customer) {
System.out.println(customer.name + "님의 잔액은 " + balance + "원 입니다.");
}
}
Test.java
package bank;
public class Test {
public static void main(String[] args) {
Customer sue = new Customer("Sue", 2000);
Account account = new Account(sue,"****"); // 계좌 생성
account.deposit(2000); // 입금
account.showAustomerInfo(sue);
account.withdrawl(3000,"****"); // 출금
account.showAustomerInfo(sue);
account.withdrawl(4000,"****"); // 잔액보다 많은 금액을 출금하려는 경우
account.showAustomerInfo(sue);
account.withdrawl(4000,"***"); // 비밀번호를 잘못 입력한 경우
}
}
수행 결과
Sue님의 계좌가 생성되었습니다.
Sue님의 잔액은 4000원 입니다.
Sue님의 잔액은 1000원 입니다.
잔액이 부족합니다.
Sue님의 잔액은 1000원 입니다.
비밀번호가 일치하지 않습니다.