copyright by Scott GrissomCh 2 Class Definition Slide 1 Class Structure public class BankAccount{ fields constructor(s) methods } Sample Code Ticket Machine (2.1)
copyright by Scott GrissomCh 2 Class Definition Slide 2 Fields stores information also called instance variables use lower case for names identify data type Examples int balance; int accountNum; String name; Draw object diagram
copyright by Scott GrissomCh 2 Class Definition Slide 3 Constructors initializes the object to an appropriate state same name as Class public BankAccount (String name, int id){ name = last; accountNum = num; balance = 0; }
copyright by Scott GrissomCh 2 Class Definition Slide 4 Accessor Methods ask object about its state method signature body generally contains a return statement recommend a name starting with ‘get’ public int getBalance ( ){ return balance; }
copyright by Scott GrissomCh 2 Class Definition Slide 5 Mutator Methods generally changes the object state might ask object to do something public void makeDeposit (int amount){ balance = balance + amount; }
copyright by Scott GrissomCh 2 Class Definition Slide 6 Print Statements displays results in the terminal window public void printStatement( ){ System.out.println(“Bank of GVSU”); System.out.println(“Name: “ + name); System.out.println(“Account #: “ + id); System.out.println(“Balance: “ + balance); System.out.println(); }
copyright by Scott GrissomCh 2 Class Definition Slide 7 Group Exercises ask questions about the TicketMachine code write a method called identityTheft that sets the balance to zero write a method makeWithdrawal that removes the provided amount from the balance write a method setBalance that replaces the existing balance with the provided amount
copyright by Scott GrissomCh 2 Class Definition Slide 8 Conditional Statements (2.11) Sample Code (2.8) if (some condition){ do if true }else{ do if false } boolean expressions –six relational operators –>, =, <=, !=
copyright by Scott GrissomCh 2 Class Definition Slide 9 Local variables temporary values public int refundBalance(){ balance = 0; return balance; } public int refundBalance(){ return balance; balance = 0; } public int refundBalance(){ int amountToRefund = balance; balance = 0; return amountToRefund; }
copyright by Scott GrissomCh 2 Class Definition Slide 10 Group Exercises result = x + y + z; result = x + y * z; result = (x + ) * z;