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);
In the code above, we use an addFraction method that takes two Fraction objects (f1, f2) as input and returns a Fraction object that we can assign to another Fraction object (f3).
The output of the above System.out.println() is:
2/3 + 1/6 = 5/6
Notice that 5/6 is a reduced fraction, meaning that somewhere in the Fraction class, there needs to be some kind of reduce() method, so the reduced form of a fraction is stored in the class.
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
We will design and implement an AccountHolder class, …
… and then we will use an AccountHolder class object as a field in a BankAccount class.
… and then we will test the BankAccount class in a program.
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
We will examine the topic of arrays that contain objects.
The arrays we have looked at before were arrays of simple, primitive types, such as int or double.
We will design and implement a Cat class, …
… and then we will use an array of Cat class objects as a field in a PetStore class.
A PetStore represents a collection of Cats (and other animals).
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?
Programmers are frequently faced with the choice of using a simple array or an ArrayList.
If the data has a known number of elements or small fixed size upper bound, or where efficiency in using primitive types is important, arrays are often the best choice.
However, many data storage problems are not that simple, and ArrayList (or one of the other
Java Collections classes) might be the right choice.
Automatic expansion
Objects only
A possible disadvantage of ArrayList is that it holds only object types and not primitive types (e.g., int, double, character).
To use a primitive type in an ArrayList, put it inside an object or use of the wrapper classes (eg, Integer, Double, Character, …).
The wrapper classes are immutable, so if you use, eg, Integer, you will not be able to change the integer value.
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