본문 바로가기

Java/과제

chapter 10) 예외처리example - BankAccount 클래스

인터페이스 과제에서 만들었던 BankAccount 클래스를 아래 내용을 참고하여 변경하여 보자.

package practice4;

public abstract class BankAccount {

	   //필드
	   protected int balance; //잔액변수
	   
	   //생성자
	   public BankAccount(int balance){
	      this.balance=balance; //잔액변수
	   }
	   //추상메소드
	   public abstract String getAccountType();
	   /**
	    * 계좌의 종류를 반환하는 메소드
	    * @return 계좌의 종류(저축예금, 당좌예금)
	    */
	   //메소드
	   public int getBalance() { 
	      return this.balance;
	   }
	   public void deposit(int amount) {   
	   }
	    public boolean withdraw(int amount) {
	       if(amount>=balance) {
	          return false;
	       }
	       balance -= amount;
	       return true;
	    }
	    
	  //tony가 steve에게 5000원 송금->송금불가
//		tonyAccount.transfer(5000, steveAccount);
	    public boolean transfer(int amount,BankAccount otherAccount) throws IllegalArgumentException{ 

	    	//5000<0||5000>4000
	       if(amount<0||amount>balance) {
	    	   //throw : 나를 호출한 곳으로 던짐
	    	   //BankExample이 BankAccount를 호출
	    	   //BankAccount에서 에러 발생 -> 에러를 나를 호출한 BankExample로 throw
	    	   System.out.println("왔다");
	    	   //사용자가 임의로 발생시키는 예외
	          throw new IllegalArgumentException();
	       }
	       //this.balance = this.balance - amount
	       //             = 4000 - 2000
	       //this.balance = 2000
	       //this : tony
	       this.balance -= amount;
	       //otherAccount : steve
	      otherAccount.deposit(amount);	//otherAccount가 null이면 nullPointException 발생
	      return true;

	    }

	    //메소드 추가
	    public String toString() {
	       return String.format("%,d",balance);
	    }
	}
package practice4;

import practice4.BankAccount;
import practice4.CheckingAccount;

public class BankExample {
	public static void main(String[] args) {
		
		//BankAccount.balance : 3000
		CheckingAccount tonyAccount = new CheckingAccount(3000);
		//BankAccount.balance : 4000
		CheckingAccount steveAccount = new CheckingAccount(4000);
		
		try {
			//tony가 steve에게 5000원 송금->송금불가
			tonyAccount.transfer(5000, steveAccount);
			System.out.println("송금 완료");
		} catch (NullPointerException e) {
			System.out.println("해당하는 계좌가 없습니다.");
			System.out.println("송금 실패");
		} catch (IllegalArgumentException e) {
			System.out.println("해당하는 금액을 보낼 수 없습니다.");
			System.out.println("송금 실패");
		}
		
		try {
			tonyAccount.transfer(2000, null);
			System.out.println("송금 완료");
		} catch (NullPointerException e) {
			System.out.println("해당하는 계좌가 없습니다.");
			System.out.println("송금 실패");
		} catch (IllegalArgumentException e) {
			System.out.println("해당하는 금액을 보낼 수 없습니다.");
			System.out.println("송금 실패");
		}
	}
}

Recent Posts
Popular Posts
Tags
더보기
Recent Comments