Private Instance Variable and Public Methods - Java Object Oriented Design

Java examples for Object Oriented Design:Access Level

Description

Private Instance Variable and Public Methods

Demo Code

public class Main {
  public static void main(String[] args) {
    MyCredit ac = new MyCredit();
    double balance = ac.getBalance();
    System.out.println("Balance = " + balance);

    ac.credit(24.718);//w  w w .j  a  v  a  2s.  c o m
    ac.debit(10.112);

    balance = ac.getBalance();
    System.out.println("Balance = " + balance);

    // Attempt to credit and debit invalid amounts
    ac.credit(-24.90);
    ac.debit(Double.POSITIVE_INFINITY);

    balance = ac.getBalance();
    System.out.println("Balance = " + balance);

    // Attempt to debit more than the balance
    ac.debit(200.00);

    balance = ac.getBalance();
    System.out.println("Balance = " + balance);
  }
}

class MyCredit {
  private double balance;
  // Return the balance of this account
  public double getBalance() {
    return this.balance;
  }

  public int credit(double amount) {
    if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) {
      System.out.println("Invalid credit amount: " + amount);
      return -1;
    }
    System.out.println("Crediting amount: " + amount);
    this.balance = this.balance + amount;
    return 1;
  }

  public int debit(double amount) {
    if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) {
      System.out.println("Invalid debit amount: " + amount);
      return -1;
    }
    // Make sure a minimum balance of zero is maintained
    if (this.balance < amount) {
      System.out.println("Insufficient fund. Debit attempted: " + amount);
      return -1;
    }
    this.balance = this.balance - amount;
    return 1;
  }
}

Result


Related Tutorials