Table of Contents

Objects in Methods, Objects as Class Fields, Arrays of Objects


Objects in Methods

     // Construct one fraction and print it
     Fraction f1;
     f1 = new Fraction(2, 3);
     System.out.println(f1);
     
     // Add two Fraction objects to get a sum Fraction object
     Fraction f2;
     f2 = new Fraction(1, 6);
     Fraction f3;
     f3 = addFraction(f1, f2);

     System.out.println(f1 + " + " + f2 + " = " + f3);
            2/3 + 1/6 = 5/6
     public static Fraction addFraction( Fraction one, Fraction two )
     {
        // Compute common denominator: 
        int dd = one.getDenominator() * two.getDenominator();
        
        // Cross multiply and add:
        int nn = one.getNumerator() * two.getDenominator() +
                 two.getNumerator() * one.getDenominator();
    
        Fraction sum = new Fraction( nn, dd );            
        return sum;
        //
        // or skip using a sum variable by doing this:
        //return new Fraction( nn, dd ); 
     }

Objects as Class Fields

     public class AccountHolder
     {
         private String firstName;
         private String lastName;
         private int age;

         // Constructors:
         /**
          * Constructor #1
          * @param first name
          * @param last name
          * @param age
          */
         public AccountHolder( String fn, String ln, int ag ) {
            firstName = fn;
            lastName = ln;
            age = ag;
         }

         /*
          * Constructor #2 (default)
          */
         public AccountHolder()
         {
         }

         // Methods:
         // Write get and set methods for firstName, lastName, age below.
         ...
     } // end class
    public class BankAccount
    {
        private int acctnum;
        private double balance;
        private AccountHolder customer;
        ...
        ...
    } // end class
    /**
     * Constructor#1 for objects of class BankAccount
     * @param acct
     * @param bal
     * @param firstname of customer
     * @param lastname of customer
     * @param age of customer
     */
    public BankAccount( int acct, double bal, String firstname, String lastname, int age )
    {
        // Write code to set account number, balance and customer name and age:
        acctNum = acct;
        balance = bal;
        // Since customer is an object, initializing it requires calling a constructor;
        // Use last 3 input parameters to construct the customer object.
        customer = new AccountHolder( firstname, lastname, age );
    }
    (Code in main() method of TestBankAccount.java)

    BankAccount myAccount;
    myAccount = new BankAccount( 1, 8000.00, "Joe", "Chung", 56 );
    // The last 3 constructor arguments, "Joe", "Chung", and 56 will
    // be passed to the AccountHolder constructor to construct a
    // customer object within the myAccount object.

Working with objects as instance variables

    /**
     * Get method for customer's information
     * @return info
     */
    public String getCustomerInfo()
    {
        // Use get methods defined in the AccountHolder class:
        String info = "Name:\t" + customer.getFirstName() + " " + customer.getLastName() + "\n" +
                      "Birthday:\t" + costomer.getBirthDay() + "\n" +
                      "Age:\t" + customer.getAge() + "\n" +;
        return info;
    }
    /**
     * Get method for customer
     * @return customer, an AccountHolder object
     */
    public AccountHolder getCustomer()
    {
        return customer;
    }
    (Code in main() method of TestBankAccount.java)

    // Get bankaccount holder's first name only:
    System.out.println("Account holder's first name: " + myAccount.getCustomer().getFirstName());

    // myAccount.getCustomer() returns the customer object that's in the myAccount object, and then
    // .getFirstName() gets the customer object's firstname.

Arrays of Objects

    public class Cat
    {
        // instance variable
        private String _name;
    
        /**
        * constructor #1
        * @param name
        */
        public Cat(String name)
        {
            _name = name;
        }
    
        // methods
        /**
        * Get method for _name
        * @return _name
        */
        public String getName()
        {
            return _name;
        }
    
    } // end class
    public class PetStore
    {
        // instance variables
        // array of Cats
        private Cat [] cats;
        private final int MAXCATS = 15;
        ...
    public PetStore()
    {
        // construct array of cats
        cats = new Cat[MAXCATS];
    }
    public void addCats()
    {
        // Add a new Cat using a Cat variable, c1
        Cat c1 = new Cat("Miu");
        cats[0] = c1;
        ...        
        // Add a new Cat without using a Cat variable
        cats[3] = new Cat("Skitty");
        ...
    }
    // Must call Cat object's getName method
    System.out.println(cats[3].getName());

The ArrayList Class

java.util.ArrayList

Arrays or ArrayList?

Automatic expansion

Objects only

Common ArrayList methods and constructors

    new ArrayList<E>()  	Creates ArrayList of Class E objects with
                            initial default capacity of 10.

    new ArrayList<E>(cap)  	Creates ArrayList with initial int
                            capacity cap.
    a.add(e)      adds element e to the end of ArrayList a
    a.add(i, e)   Inserts e at index i, shifting elements up as necessary.
    a.set(i,e)    Sets the element at index i to e.
    a.get(i)      Returns the object at index i.
    a.toArray()   Returns elements in a as an array of objects.
    a.clear()             Removes all elements from ArrayList a
    a.remove(i)           Removes the element at position i.
    a.removeRange(i, j)   Removes the elements from positions i thru j.
    a.size()   Returns the number of elements in ArrayList a.

Adding elements to the end of an ArrayList, getting them by index

    ArrayList<E> a = new ArrayList<E>();  // Construct default size ArrayList a

    E s = new E();     // Construct s object of Class E.

    . . .

    a.add(s);     // Add object s to the end of the ArrayList a

    . . .

    s = a.get(i); // Assigns i-th element from a to object s.

To get successive elements from an ArrayList

    ArrayList<String> a = new ArrayList<String>();
    . . .
    for ( String s : a ) {
       System.out.println( s );
    }
    // Assume a is an ArrayList:
    for ( int i = 0; i < a.size(); i++ ) {
       System.out.println( a.get( i ) );
    }

Sorting

    Collections.sort(yourArrayList);
    // Purpose: An exercise using Scanner, ArrayList, and
    //          Collections.sort.  Read words, sort them, print
    //          them.

    import java.util.Scanner;
    import java.util.ArrayList;
    import java.util.Collections; // for sorting method    

    public class Alphabetize
    {
       public static void main(String[] args)
       {
          //... Declare variables.
          Scanner in    = new Scanner(System.in);
          ArrayList<String> words = new ArrayList<String>();

          //... Read input one word at a time.
          System.out.println("Enter words.  End with EOF (ex. CTRL-Z then Enter, or CTRL-D)");

          //... Read input one word at a time, adding it to an array list.
          while (in.hasNext()) {
             words.add(in.next());
          }

          //... Sort the words.
          Collections.sort(words);

          //... Print the sorted list.
          System.out.println("\n\nSorted words\n");

          // foreach loop:
          for (String word : words) {
             System.out.println(word);
          }
            
       } // end main
    } // end class