0% found this document useful (0 votes)
24 views

Week 2: Building Multi-Class Applications: Choosing Classes

This document discusses building multi-class applications in Java. It provides an example of restructuring a Purse class into separate Coin and Purse classes to represent single concepts. The relationship between these classes is represented in a UML class diagram using arrows. An example invoice application is presented using classes for Invoice, Address, Product, and LineItem. The document also provides an example university application center program using classes for ApplicationCentre and StudentApplication to manage student applications.

Uploaded by

a3251332
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Week 2: Building Multi-Class Applications: Choosing Classes

This document discusses building multi-class applications in Java. It provides an example of restructuring a Purse class into separate Coin and Purse classes to represent single concepts. The relationship between these classes is represented in a UML class diagram using arrows. An example invoice application is presented using classes for Invoice, Address, Product, and LineItem. The document also provides an example university application center program using classes for ApplicationCentre and StudentApplication to manage student applications.

Uploaded by

a3251332
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Week 2: Building Multi-Class Applications

Choosing Classes
- objects correspond to nouns in the description of your application
- their behaviour corresponds to public methods contained in their corresponding classes
- choosing classes is not a trivial task
- create classes which represent a single concept (see Ex.2.1)

Class Purse shown below there are 2 concepts: a purse that holds coins and the value of each
coin.

class Purse {
public Purse();
public void addNickels(int count);
public void addDimes(int count);
public void addQuarters(int count);
public double getTotal();

}
It is therefore better to rewrite the class as:
class Coin{
public Coin(double value, String aName);
public double getValue();
}
class Purse {
public Purse();
public void add(Coin aCoin);
public double getTotal();
}

In this case class Purse depends on class Coin as it is using objects of Coin type. Of course, class
Coin does not depend on class Purse.

UML class diagrams


The world of classes and objects is conveniently presented in the Unified Modeling Language
(UML) diagrams.
In UML the relationship between Purse and Coin is represented with an arrow pointing to Coin,
the dependent class:

If class Coin changes that will imply that class Purse has to be rewritten. In general you want to
minimize the number of class dependencies (low coupling).
UML Class connectors:
- arrow for Inheritance
- arrow with a romb instead of > for Aggregation (as in the example above)
- dashed arrow for Dependency

Case Study: Printing an Invoice


An Invoice object must hold references to the Address and the LineItems. The Product is turned
into a LineItem object. Invoice contains an ArrayList of LineItems.

public class InvoiceTester{


public static void main(String[] args) {
Address samsAddress
= new Address("Sam's Small Appliances",
"100 Main Street", "Anytown", "CA", "98765");
Invoice samsInvoice = new Invoice(samsAddress);
samsInvoice.add(new Product("Toaster", 29.95), 3);
samsInvoice.add(new Product("Hair dryer", 24.95), 1);
samsInvoice.add(new Product("Car vacuum", 19.99), 2);
System.out.println(samsInvoice.format());
}
}
public class Invoice{
public Invoice(Address anAddress) {
items = new ArrayList<LineItem>();
billingAddress = anAddress;
}

public void add(Product aProduct, int quantity) {


LineItem anItem = new LineItem(aProduct, quantity);
items.add(anItem);
}
public String format()
{
String r = "
I N V O I C E\n\n"
+ billingAddress.format()
+ String.format("\n\n%-30s%8s%5s%8s\n",
"Description", "Price", "Qty", "Total");
for (LineItem i : items)
{
r = r + i.format() + "\n";
}
r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());
return r;
}
public double getAmountDue() {
double amountDue = 0;
for (LineItem i : items)
{
amountDue = amountDue + i.getTotalPrice();
}
return amountDue;
}
private Address billingAddress;
private ArrayList<LineItem> items;
}
public class Address{
public Address(String aName, String aStreet,
String aCity, String aState, String aZip) {
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = aZip;
}
public String format() {
return name + "\n" + street + "\n"
+ city + ", " + state + " " + zip;
}
private String name;
private String street;
private String city;
private String state;
private String zip;
}
public class LineItem{
public LineItem(Product aProduct, int aQuantity) {

theProduct = aProduct;
quantity = aQuantity;
}
public double getTotalPrice() {
return theProduct.getPrice() * quantity;
}
public String format() {
return String.format("%-30s%8.2f%5d%8.2f",
theProduct.getDescription(), theProduct.getPrice(), quantity, getTotalPrice());
}
private int quantity;
private Product theProduct;
}
public class Product {
public Product(String aDescription, double aPrice) {
description = aDescription;
price = aPrice;
}
public String getDescription() {
return description;
}
public double getPrice() {
return price;
}
private String description;
private double price;
}

Case Study: Application Centre for universities admissions.


A student can choose 3 different universities and let us assume that this center will accept up to
100 different applications. This program has to allow the user to:
i) enter the student application,
ii) accept students in some of the universities that they chose
iii) display the status of the applications.
The two obvious classes are the ApplicationCentre and the Student. The Student class is the
dependent class but unlike in the previous example the relationship between the two classes is of
the type one-to-many. The following UML class diagram will specify the relation between
Student and ApplicationCentre.
ApplicationCentre
- st[100] : StudentApplication
+ addStudent(): boolean
+ getStudent(int):StudentApplication

StudentApplication
- univ1, univ2, univ3: String
- acc1, acc2, acc3: boolean
- name : String
+ setAcceptance(): void
+ toString(): String

Note: A UML object diagram contains a snapshot of the objects at a certain point in the
execution of the program. The notation will include the names of the objects and the values of
the attributes.
We shall note use UML object diagrams in this course.
Java Implementation of the Applications Centre
The Applications class presented below is the driver which allows for
the association of ApplicationCentre and StudentApplication classes. For input/output we shall
use JOptionPane, a class part of the Swing package which produces simple pop-up dialog boxes.
(in most of this course we shall avoid the line input/output used in ITEC1620)
Ex.2.2
// A class which handles applications for university admission
import javax.swing.JOptionPane;
public class Applications {
public static void main( String args[] ) {
ApplicationCentre appCentre= new ApplicationCentre ("Guelph");
String stopper="quit";
int nrStud=0;
StudentApplication s;
// Input data
JOptionPane.showMessageDialog(null,"Enter student names, each followed by 3 choices of universities. To
stop enter for name the word quit","Input", JOptionPane.PLAIN_MESSAGE);
String n = JOptionPane.showInputDialog("Student's name ?");
boolean flag=true;
while (!n.equals(stopper) && flag){
String u1= JOptionPane.showInputDialog("1st university ?");

String u2= JOptionPane.showInputDialog("2nd university ?");


String u3= JOptionPane.showInputDialog("3rd university ? ");
s=new StudentApplication (n, u1, u2, u3);
flag=appCentre.addStudent(s);
n=JOptionPane.showInputDialog("Student's name ?");
nrStud++;
}
// Accept some applications
String line = JOptionPane.showInputDialog(" Indicate which applications are to be accepted by entering
the student index number. To stop enter for name the word quit");
while (!line.equals(stopper)) {
int stnr=Integer.parseInt(line);
line= JOptionPane.showInputDialog("Enter university index 0..2");
int anr=Integer.parseInt(line);
s = appCentre.getStudent(stnr);
s.setAcceptance(anr);
line= JOptionPane.showInputDialog(" Indicate which applications are to be accepted by entering the
student index number. To stop enter for name the word quit");
}
// Print the final results
JOptionPane.showMessageDialog(null, " Records for all applicants to "+ appCentre.getName() +
"\n","Records", JOptionPane.PLAIN_MESSAGE);
for (int i=0;i<nrStud; i++)
s = appCentre.getStudent(stnr);
JOptionPane.showMessageDialog(null, s.toString() ,"Records", JOptionPane.PLAIN_MESSAGE);
}
}

class ApplicationCentre {
private String name;
private StudentApplication [] st;
private int studentCount;
private int size;
public ApplicationCentre(String s){
name=s;
size=100;
st = new StudentApplication[size];
studentCount=0;
}
public String getName() {
return name;
}
public boolean addStudent(StudentApplication s){
if (studentCount==size) return false;
st[studentCount]=s;
studentCount ++;
return true;
}

public StudentApplication getStudent(int which){


if (which<0 || which > studentCount-1){
return null;
}
return st[which];
}
}
class StudentApplication{
private String name;
private String university0;
private String university1;
private String university2;
private boolean accept0;
private boolean accept1;
private boolean accept2;
public StudentApplication (String n, String u0, String u1, String u2){
name = n;
university0=u0;
university1=u1;
university2=u2;
accept0=accept1=accept2=false;
}
public void setAcceptance(int which){
switch(which){
case 0: accept0=true; break;
case 1: accept1=true; break;
case 2: accept2=true; break;
}
}
public String toString(){
String result = name + ":\n";
result += university0;
if (accept0) result += " - accepted\n";
else result += " - rejected\n";
result += university1;
if (accept1) result += " - accepted\n";
else result += " - rejected\n";
result += university2;
if (accept2) result += " - accepted\n";
else result += " - rejected\n";
return result;
}
}

The most important concept in this program is the creation and use of the array
of StudentApplication objects st[].

The lines
size=100;
st = new StudentApplication[size];

in the ApplicationCentre constructor creates an array of null references:

The lines
StudentApplication s=new StudentApplication (n, u1, u2, u3);
flag=appCentre.addStudent(s);

in the main() of class Applications create the object s of StudentApplication type and then
through
the method addStudent() of class ApplicationCentre the address of s is passed to an element of
the st[ ] array.

This operation is repeated in the while loop until either the array is full or the user
enters the word quit as the name of the student.

You might also like