JavaCode(review)

Account coding / access modifier 'private' example

◀ ▷ ▶ ♤ ♠ ♡ ♥ ♧ ♣ ⊙e 2020. 6. 28. 23:47
반응형

Account coding - 거래 array / 입금/ 출금 /잔액 계산  - (출금 코딩 참고.)

 

Account Class - private 이용

package com.timbuchalka;

import java.util.ArrayList;

/**
 * Created by dev on 19/11/2015.
 */
public class Account {
    private String accountName;			// 'private' : access directly하게 불가
    private int balance = 0;
    private ArrayList<Integer> transactions;

    public Account(String accountName) {			//constructor
        this.accountName = accountName;
        this.transactions = new ArrayList<Integer>();
    }

    public int getBalance() {			//getter
        return balance;
    }

    public void deposit(int amount) {			//입금
        if(amount > 0) {
            transactions.add(amount);
            this.balance += amount;
            System.out.println(amount + " deposited. Balance is now " + this.balance);
        } else {
            System.out.println("Cannot deposit negative sums");
        }
    }

    public void withdraw(int amount) {			//출금
        int withdrawal = -amount;
        if(withdrawal < 0) {
            this.transactions.add(withdrawal);
            this.balance += withdrawal;
            System.out.println(amount + " withdrawn. Balance is now " + this.balance);
        } else {
            System.out.println("Cannot withdraw negative sums");
        }
    }

    public void calculateBalance() {			//잔액 계산
        this.balance = 0;
        for(int i : this.transactions) {
            this.balance += i;
        }
        System.out.println("Calculated balance is " + this.balance);
    }

}

Main

 

package com.timbuchalka;

public class Main {

    public static void main(String[] args) {
	    Account timsAccount = new Account("Tim");
        timsAccount.deposit(1000);
        timsAccount.withdraw(500);
        timsAccount.withdraw(-200);
        timsAccount.deposit(-20);
        timsAccount.calculateBalance();
        // timsAccount.balance = 5000;				//private이라 direct access 시도시 오류

        System.out.println("Balance on account is " + timsAccount.getBalance());
        timsAccount.transactions.add(4500);		//private -> 오류
        timsAccount.calculateBalance();
    }
}