Chapter 2:


C201 Home Page


Chapter 2
Understanding class definitions  

powered by FreeFind

Modified: 

Overview

Chapter 1 presented the general concepts behind object oriented programming and the skills needed for creating and using objects from predefined classes. Here we will define and refine these concepts more precisely and more detailed. We will also examine how to take different actions dependent upon a condition being true or false.

2.1 Ticket machines

Train station ticket machines print a ticket when the correct money is inserted. We define a class that models a naive ticket machine where:

Exercise 1

In BlueJ

  1. Open project: C201\Projects\Chapter02\naive-ticket-machine
  2. In BlueJ menu:
    • Click View
    • Check Show Terminal.
  3. In Terminal Window:
    • Click Options
    • Check Record method calls.
  4. Create an instance of the class using TicketMachine(ticketCost) constructor.
    • Supply an int parameter for the ticketCost in cents for $1.00.
  5. Complete Exercise 2.1-2.4 on page 18 of the text.

    Exercise 2.1

    1. Try the getPrice method.
      • What does it do?
      • What is the return class?
    2. Insert some money and check the balance using methods:
      • insertMoney
      • getBalance
    3. Inspect the object.
    4. Insert more money that a ticket costs.
    5. Call method printTicket.

    Exercise 2.2

    • Check the balance.
    • What is the balance after printTicket method is called?
    • Is that reasonable?

    Exercise 2.3

    • Experiment by inserting different amounts of money before calling printTicket method.
    • What is the balance after printTicket method is called?
    • What must happen to balance field in printTicket method?

    Exercise 2.4

    • Experiment with the TicketMachine class before we examine in in detail.
    • Create another TicketMachine object with a different ticket price.
    • Buy and print a ticket.
    • Does the ticket look much the same?
    • Is that reasonable behavior? Why?

2.2 Examining a class definition

The TicketMachine class definition source code of page 20 with comments removed.

 public class TicketMachine
 {
 private int price;
 private int balance;
 private int total;
 public TicketMachine(int ticketCost)
 {
       price = ticketCost;
       balance = 0;
       total = 0;
 }
 public int getPrice()
 {
       return price;
 }
 public int getBalance()
 {
       return balance;
}
 public void insertMoney(int amount)
 {
       balance += amount;
 }
 public void printTicket()
 {
       System.out.println("##################");
       System.out.println("# The BlueJ Line");
       System.out.println("# Ticket");
       System.out.println("# " + price + " cents.");
       System.out.println("##################");
       System.out.println();

       total += balance;
       balance = 0;
 }
 }

2.3 Fields, constructors and methods

Exercise 2
  1. What are the field names?
  2. What is the constructor name?
  3. What are the method names?
  4. Where does TicketMachine class begin and end?
  5. Give the beginning and ending of classes Picture, Circle, Student and LabClass?
  6. How do constructors and methods appear different?

2.3.1 Fields

Field definitions

 private int price;
 private int balance;
 private int total;
Object named ticketMachine_1,
an instance of TicketMachine class.
It corresponds to the field definitions. 

2.3.2 Constructors

TicketMachine Constructor                               

 public TicketMachine(int ticketCost)
 {
       price = ticketCost;
       balance = 0;
       total = 0;
 }

Object constructed by:

 TicketMachine (43)
 

price = ticketCost;

balance = 0;

2.3.3 Passing data via parameters

 

public TicketMachine(int ticketCost) - Formal parameter is ticketCost.

 

TicketMachine( 43 ) - Actual parameter is 43.

Passing actual parameter 43 to formal parameter ticketCost.

 

public TicketMachine( int ticketCost)     

 

TicketMachine ticketMachine_1 = new TicketMachine( 43 );

 


TicketMachine( 43 )

The scope (where known) of formal parameter ticketCost is TicketMachine constructor.
 
 public TicketMachine(int ticketCost)
 {
       price = ticketCost;
       balance = 0;
       total = 0;
 }
  

The scope of field balance is TicketMachine constructor,  getBalance, insertMoney and all other TicketMachine methods.

 public int getBalance()
 {
       return balance;
}

 

 public void insertMoney(int amount)
 {
       balance += amount;
 }

 

Exercise 3 - Formal Parameters, Fields and Scope
 public int getPrice()
 {
       return price;
 }
 private int price;
 private int balance;
 private int total;
  1. What is the formal parameter of insertMoney method?
  2. What is the formal parameter of getPrice method?
  3. What is the scope of amount?
  4. Can balance be used in method getPrice?
  5. Can amount be used in method getPrice?
  6. Try in BlueJ.
    • In method getPrice change return price; to return amount;
    • Compile.
    • What happened and why?

2.5 Assignment

int balance;       
balance = 40*3;                  
String name;
name = "Fred";                 
boolean onFire;
onFire = true;

For now, both sides must be the same data type: int, String, or boolean.

Exercise 3.5 - Assignment and Expressions
 
 int balance;                  String name;                  boolean onFire;

What is the value of the following?

  1. balance = 40*3+2;
  2. name = "Fred" + "Flintstone";
  3. onFire = true or false;

2.6 Accessor methods

Four methods of TicketMachine:

 public int getPrice()
 {
       return price;
 }
 public int getBalance()
 {
       return balance;
}
 public void insertMoney(int amount)
 {
       balance += amount;
 }
 public void printTicket()
 {
       System.out.println("##################");
       System.out.println("# The BlueJ Line");
       System.out.println("# Ticket");
       System.out.println("# " + price + " cents.");
       System.out.println("##################");
       System.out.println();

       total += balance;
       balance = 0;
 }
/**
 * Return the price of a ticket.
 */
 public int getPrice()
 {
       return price;
 }
Comment
 

Header or signature

Body

/**
 * Receive amount of money in cents from a customer.
 */
 public void insertMoney(int amount)   
 {
       balance += amount;
 }
Comment
 

Header or signature

Body

Exercise 4 -Methods
  1. How does the header of getPrice and insertMoney differ?
  2. How does the body of getPrice and insertMoney differ?
  3. Try in BlueJ.
    • Remove the return price; statement from getPrice.
    • Compile
    • What happened and why?
  4. Write an accessor method getTotal that returns the total field value.
    • Compile and test.

2.7 Mutator methods

Assignment changes a variable, such as a field. Calling method printTicket mutates the field balance = 0;

 
 public void insertMoney(int amount)   
 {
       balance += amount;
 }
 
public void printTicket()
 {
       System.out.println("##################");
       System.out.println("# The BlueJ Line");
       System.out.println("# Ticket");
       System.out.println("# " + price + " cents.");
       System.out.println("##################");
       System.out.println();

       total += balance;
       balance = 0;
 }

 

Exercise 5 - Mutators                                                               
  • In BlueJ:
    • Create a TicketMachine object with a positive ticket price.
    • Inspect the object doing the following calls:
      1. Call insertMoney method on the object, inserting 53 cents.
      2. Call insertMoney method on the object, inserting 47 cents. Is insertMoney a mutator or accessor method?
      3. Call printTicket method on the object. Is printTicket a mutator or accessor method?
Exercise 6 - Assignment   
  1. What is the value of balance after each statement:

    balance = 40;
    balance = 20;
    balance = 10;
     

  2. What is the value of balance after each statement:

    balance = 40;
    balance = balance + 20;
    balance = balance + 10;

  3. What is the value of balance after each statement:

    balance = 40;
    balance += 20;
    balance += 10;                                                    

2.8 Printing from methods

Printing object ticketMachine_1

 
public void printTicket()
 {
       System.out.println("##################");
       System.out.println("# The BlueJ Line");
       System.out.println("# Ticket");
       System.out.println("# " + price + " cents.");
       System.out.println("##################");
       System.out.println();

       total += balance;
       balance = 0;
 }
 

##################
# The BlueJ Line
# Ticket
# 43 cents.
##################

  1. "abc"+"def" is "abcdef"
  2. "12"+3 is "123". The integer 3 is converted to a String "3" and then "12" +"3" is concatenated.
Exercise 7 - Printing and String Concatenation
  1. What is printed by the following?

    System.out.println("# The BlueJ Line");

  2. What is printed by the following when price is 54?

    System.out.println("# " + price + " cents.");

  3. What is the result of the following when price is 54?
    1.  "# " + price + " cents."
    2. "ab" + "c"
    3. 34 + 5
    4. "34"+"5"
    5. "34"+"5"
    6.  "# " +"price" + " cents."
    7.  "# + price + cents."

In BlueJ:

  1. Create the TicketMachine object above.
    • Inspect the object.
    • Call the printTicket method on the object.
  2. Exercise 2.19, page 33. Add a method prompt to the TicketMachine class. The method has void return type and no parameters. The method body should print:

    Please insert the correct amount of money.

  3. Exercise 2.20, page 33. Add a method showPrice to the TicketMachine class. The method has void return type and no parameters. The method body should print:

    The price of a ticket is xyz cents.

    where xyz is replaced by the value of price field when the method is called.

  4. Exercise 2.22, page 33. Add a method showPrice to the TicketMachine class. The method has void return type and no parameters. The method body should print:

    The price of a ticket is xyz cents.

2.9 Summary of the naive ticket machine

Exercise 8 - TicketMachine

In BlueJ   

  1. Implement another TicketMachine constructor:
    • with no ticketPrice parameter
    • price is fixed at 1000 cents
    • create a TicketMachine object using your new constructor
    • create a TicketMachine object using the old constructor and an actual parameter for a ticket price of 54 cents.
    • Inspect both objects. You should have two inspector windows. Is there any difference in the two objects?
    • Call insertMoney method using both objects.
    • Call printTicket method using both objects. Is there any difference in the two objects?

In your head

  1. Exercise 2.26, page 34.

    Why does the following version of refundBalance not give the same results as the original?

    public int refundBalance()
    {
        balance = 0;
        return balance;
    }

    What tests can you run to demonstrate that it does not?

  2. Exercise 2.27, page 34.

    What happens if you try to compile the TicketMachine class with the following version of refundBalance:

    public int refundBalance()
    {
            return balance;
            balance = 0;
    }

    What do you know about return statements that explain why this version is incorrect?

2.10 Reflecting on the design of the ticket machine

  1. No check that enough money inserted to pay for ticket.
  2. No check that sensible amount of money inserted, can insert negative amounts of money.
  3. No check that ticket price of constructor is sensible.
  4. No refund when too much money inserted.

2.11 Making choices: the conditional statement

  1. Check that enough money inserted to pay for ticket.
  2. Checks that sensible amount of money inserted, can insert negative amounts of money.
  3. No check that ticket price of constructor is sensible.
  4. No refund when too much money inserted.
Exercise 9 - Conditionals    

In BlueJ: 

  1. Open the better-ticket-machine project.
  2. Create a TicketMachine object:
    • with a ticketPrice parameter of 25 cents.
  3. Inspect the object.
  4. Call insertMoney method with amount parameter of -45 cents.
    • What happened to the object state?
  5. Call insertMoney method with amount parameter of 5 cents.
    • What happened to the object state?
  6. Call printTicket method.
    • What happened to the object state?
    • Explain how total changed.
    • Explain how balance changed.
  7. Call insertMoney method with amount parameter of 50 cents.
    • What happened to the object state?
  8. Call printTicket method.
    • What happened to the object state?
    • Explain how total changed.
    • Explain how balance changed.
Exercise 10 - if else conditionals

What are the following when:

  • amount = 54
  • balance = 10
  • correct = true
  1. 4 > 5
  2. if (4 > 5 ) { balance = 6 } else { balance = 7 };
  3. 4 <= 5
  4. if ( 4 <= 5) { balance = 6 } else { balance = 7 };
  5. "a" < "b"
  6. "abc" < "ab"
  7. amount > 50
  8. if  (amount > 50 ) { balance = 6 } else { balance = 7 };
  9. amount -10 > 50
  10. if  (amount - 10 > 50 ) { balance = 6 } else { balance = 7 };
  11. if  (amount > 0 ) {
         balance += amount
    }  
    else {
         System.out.println( "Use a positive amount: " + amount );
    }
  12. if  ( true ) { balance = 6 } else { balance = 7 };
  13. if  ( correct ) { balance = 6 } else { balance = 7 };

Changes to naive-ticket-machine to make the better-ticket-machine

 public class TicketMachine
 {
 public void insertMoney(int amount)
 {
        if(amount > 0) {
              balance += amount;
       }
       else {
              System.out.println("Use a positive amount: " + amount);
       }
 }
 public void printTicket()
 {
        if(balance >= price) {
              System.out.println("##################");
              System.out.println("# The BlueJ Line");
              System.out.println("# Ticket");
              System.out.println("# " + price + " cents.");
              System.out.println("##################");
              System.out.println();

              total += price;
              balance -= price;
       }
       else {
              System.out.println("You must insert at least: " + (price - balance) + " more cents.");
       }
 }
  public int refundBalance()
 {
       int amountToRefund;
       amountToRefund = balance;
       balance = 0;
       return amountToRefund;
 }
 }

2.12 A further conditional-statement example

See printTicket above.

Exercise 11 - printTicket
  • Exercise 2.33, page 39. After a ticket has been printed, could the value of balance field ever be set to a negative value by subtracting price? Justify your answer.

2.13 Local variables

  public int refundBalance()
 {
       int amountToRefund;

       amountToRefund = balance;
       balance = 0;
       return amountToRefund;
 }
Exercise 12 - Local variables  

In BlueJ:

  1. Open the better-ticket-machine project.
  2. Create a TicketMachine object:
    • with a ticketPrice parameter of 25 cents.
  3. Inspect the object.
    • Is amountToRefund variable a field of the object?
  4. Call insertMoney method with amount parameter of 45 cents.
    • What happened to the object state?
  5. Call refundBalance method.
    • What happened to the object state?
    • What value was returned?
  6. Add the following line in method printTicket:

    balance -= price;
    amountToRefund = 0;

    • Compile. What does the error message mean?
       
  7. Correct printTicket method by deleting the added line.
  8. Change the local variable definition to a comment as follows:
    • // int amountToRefund;
  9. Compile TicketMachine.
    • Why is there an error message?
  10. Exercise 2.35, page 40.
  11. Local variables are temporary. Each time a method is called, the local variables are created. When the method returns, the local variables are destroyed.

    What is printed by 4 calls to the method:

     public void Exercise12() {
         int count = 0;
         count = count + 1;
         System.out.println(count);
    }

     

2.14 Fields, parameters and local variables

Read text, page 40.

Exercise 13 - Fields, parameters and local variables

In BlueJ:

  1. Exercise 2.36, page 41.
    • Add a new TicketMachine method, emptyMachine, that models emptying the machine of money.
    • The method should return the value in total and set total to 0.
    • Create an object with a ticket price of 45 cents.
    • Inspect.
    • Call insertMoney method with 73 as the actual parameter.
    • Call emptyMachine method to test.
  2. Exercise 2.37, page 41. Is emptyMachine an accessor, mutator, or both?
  3. Exercise 2.38, page 41. Rewrite printTicket method:
    • declare a local variable amountLeftToPay
    • initialize amountLeftToPay to the difference between price and balance
    • Rewrite the conditional to check amountLeftToPay <= 0
      • if true, print a ticket
      • else print an error message stating the amount still required
    • Create an object with a ticket price of 45 cents.
    • Inspect.
    • Test both conditions:
      • Call insertMoney method with 44 as the actual parameter.
      • Call printTicket method. Was the result as expected?
      • How can the other condition be tested? Test to verify.

2.15 Summary of the better ticket machine

2.16 Reviewing a familiar example

 public class Student
 {
    private String name;
    private String id;
    private int credits;

    public Student(String fullName, String studentID)
   {
        name = fullName;
        id = studentID;
        credits = 0;
    }

    public String getName()
    {
        return name;
    }

    public void changeName(String replacementName)
    {
        name = replacementName;
    }

    public String getStudentID()
    {
        return id;
    }

    public void addCredits(int additionalPoints)
    {
        credits += additionalPoints;
    }

    public int getCredits()
    {
        return credits;
    }

    public String getLoginName()
    {
        return name.substring(0,4) + id.substring(0,3);
    }

    public void print()
    {
        System.out.println(name + " (" + id + ")");
    }

 }

 

Exercise 14 - Review and String methods
  1. "01234567".substring(2,5) is the String "234". Assume the name field is "012345". What is:
    1. "01234567".substring(4,5)
    2. "01234567".substring(4,7)
    3. "01234567".substring(4,10)
    4. name.substring(0,3)
    5. name.substring(-1,3)
  2. "01234567".length() is the integer 8. Assume the name field is "012345". What is:
    1. "01234".length()
    2. "Harvey".length()
    3. name.length()
    4. "01234".substring(1,4).length()
    5. name.substring(0,5).length()

In BlueJ:

  1. Open project C201\Projects\chapter01\lab-classes
    • Examine in the editor.
  2. Student class contains how many:
    • fields
    • constructors
    • mutators
    • accessors
  3. What do the accessor names have in common?
  4. Exercise 2.40, page 44.
    • What would be returned by getLoginName for a student with the name "Henry Moore" and the id "557214"?
  5. Exercise 2.41, page 44.
    • Create a Student with name "djb" and id "859012". What happens when getLoginName is called on this student? Why do you think this is?
  6. Exercise 2.42, page 44.
  7. Exercise 2.43, page 44.

2.17 Summary

 public class Book
 {
    private String author;
    private String title;

    public Book( String bookAuthor, String bookTitle )
   {
       author = bookAuthor;
       title = bookTitle;
    }

 }

 

Exercise 15 - Creating a class

In BlueJ:

  1. Open project C201\Projects\chapter01\lab-classes
    • Examine in the editor.
  2. Exercise 2.45, page 47.
  3. Exercise 2.46, page 47.



C201 Home Page


Please send any comments to: jfdoyle@ius.edu 
Copyright © 2001-2004 by cgranda@ius.edu . All rights reserved.