Transcript Objects

Computing Fundamentals with Java
3-1
Rick Mercer
Franklin, Beedle & Associates, 2002
ISBN 1-887902-47-3
Chapter 3
Using Objects
Presentation Copyright 2002, Rick Mercer
Students who purchase and instructors who adopt Computing Fundamentals with Java by Rick Mercer
are welcome to use this presentation as long as this copyright notice remains intact.
Objects
3-2
 Java has two types of data:

primitive types that store one value
char

boolean
byte
int
long
float
double
reference types for constructing objects that may
store many values

any of the hundreds of classes that come with Java
String

BufferedReader
JButton
any domain classes for specific applications
BankAccount

URLAddress
Student
Jukebox
Classes that provide utility
TextReader
DecimalFormat
CD
3-3
Objects
 Objects model real world entities that are more
complex than numbers.
 An object is one instance of a class.
 A class is a collection of related methods and data
needed by the methods to fulfill their
responsibilities.
 A class is a blueprint for constructing many objects.
 An OO system is a collection of objects that send
messages to themselves and other objects.

Identify objects that model real world things (next slide)
3-4
Find real world entities
Implement a bank teller application that provides many
bank customers access to bank accounts through a
unique ID. The customer, with the help of the teller,
may complete any of the following transactions:
withdraw money, deposit money, query account
balances, and see the most recent ten (10)
transactions. The system must maintain the correct
balances for all accounts. The system must be able to
process one or more transactions for any number of
customers. The following window summarizes the
system functionality:
3-5
BankTeller Window
Code is in section 3.7 and on the book's disk
3-6
Nouns are possible classes
 Potential objects to model a solution:








BankTeller
Customer
BankAccount
IdentificationNumber
Transaction
ListOfTransactions
MonthlyStatement
Let's consider one of these objects as a collection of
methods and stored data.
A BankAccount class
3-7
 BankAccount models an account at a bank.
 This class could have a collection of methods to
allow for operations like these:
withdraw( 50.00
deposit( 152.27
getBalance() //
getID()
//
)
)
return account balance
return account identification
 The class could allow all instances to have state
(values) such as this:


an ID such as "Little, Stuart"
a balance such as 507.99
3-8
Constructing objects
 The BankAccount class is not part of Java.

It is domain specific
 Each BankAccount object must be constructed with
two values:


A String to initialize the ID
A number that represents the current balance
// Construct a BankAccount object with 2 arguments
BankAccount anAccount = new BankAccount("Kim", 100.00);
3-9
What is an Object in the
computer?
 An object is a bunch of bits in the computer memory.
 Every object has:
1) a name
2) a set of messages that it understands
3) state the values that the object remembers
 The state is usually initialized at construction.

the state is stored in instance variables
 Once constructed, you can send messages to these objects.
3-10
Constructing objects
 Primitive types may be initialized with one value:
int n = 0;
double x = 0.000001;
 General Form (creating an instance of a class)
class-name identifier = new class-name(initial-value(s));
 Some classes require 0, 1, 2, 3, or more arguments:
JFrame theWindow = new JFrame( );
ArrayList list = new ArrayList( );
JButton clickMeButton = new JButton("Nobody's listening");
Font aFont = new Font( "Courier", Font.ITALIC, 24 );
BankAccount myAcct = new BankAccount("Bob", 123.45);
GregorianCalendar aDay = new GregorianCalendar(2001,1,1);
Sending Messages
3-11
 Each class has a collection of methods.

BankAccount has


withdraw, deposit, getID, and getBalance
String has

length, indexOf, charAt, toUpperCase toLowerCase
 A method is invoked via a message.
 A message has a sender (main e.g.), a receiver
(the object), a message-name and the arguments.
object name . messsage-name( arguments )
3-12
Messages
 Some messages return information about an
object's state.
 Other messages tell an object to do something.

A message that asks the object to return information:
anAccount.getBalance( );

A message that tells the object to do something:
anAccount.withdraw( 25.00 );
3-13
Messages continued
 General Form: sending a message to an object
object-name . method-name ( argument-list )
 Example Messages:
anAccount.deposit( 100.00 );
name.toUpperCase( );
theWindow.setSize( 200, 400 );
theTextField.setText( "A different String" );
theTextField.getText( );
3-14
Sending messages in a program
public class TestAccount1
{
public static void main( String[] args )
{
BankAccount anAcct = new BankAccount( "Stoers", 200.0 );
BankAccount acct2 = new BankAccount( "Daly", 325.00 );
anAcct.deposit( 133.33 ); // Send a deposit message
acct2.withdraw( 250.00 ); // Send a withdraw message
// Ask both BankAccount objects to return information
System.out.println( anAcct.getID() + ": "
+ anAcct.getBalance( ) );
System.out.println( acct2.getID() + ": "
+ acct2.getBalance( ) );
}
}
Write the Output ? _________________ ?
3-15
Class and Object Diagrams
 Relationship between a class and it objects.

Each object stores its state in instance variables
class name
BankAccount
instance
variables
-String my_ID
-double my_balance
methods
+withdraw(double amount)
+deposit(double amount)
+double getBalance( )
+String getID( )
+String toString()
BankAccount: anAcct
my_ID = "Stoers"
my_balance = 333.33
BankAccount: acct2
instance
(object)
state
instance
(object)
my_ID = "Daly"
my_balance = 75.00
state
3-16
The String class
 Java has a class for manipulating a collection of
characters.

The character set could be any of the hundreds in the
world, we'll use the ASCII character set
 String methods include:
substring
toUpperCase
charAt
length
indexOf
3-17
Example String Messages
// Construct two String objects
String aStr = new String( "Any old" );
String s = new String( aStr + " String" ); // Concatenate
// s is now "Any old String"
// Show the first character at position 0, not 1
System.out.println( s.charAt( 0 ) );
// Show the upper case equivalent
System.out.println( "toUpperCase: " + s.toUpperCase( ) );
// Show the number of characters currently in the string
System.out.println( "length: " + s.length( ) );
// Show the position of "ring" in "Any old string"
System.out.println( "indexOf: " + s.indexOf( "ring" ) );
3-18
Shortcut String object
construction
 In Java, "abc" is an object, but 1 and 1.5 are not.
 In SmallTalk, 1 and 1.5 are objects.
// s2 is initialized as if it were a primitive
String s2 = "Don't need new String( "Abc" )";
System.out.println( s2 ); // OKAY
 Consider always giving the object a value
// Compiler will say: "s1 may not be initialized"
String s1;
System.out.println( s1 ); // Compiletime ERROR
3-19
String Input
 The TextReader class has two methods for
reading string input.
TextReader keyboard = new TextReader( );

readline returns all the characters typed on one line
String theEntireLine = keyboard.readLine( );

readWord returns one string separated by white space
input blank characters, tabs, or end of lines
String aStringWithNoBlanks = keyboard.readWord();
3-20
String Input
public class StringInputMethods
{
public static void main( String[] args )
{
String firstName, address;
TextReader keyboard = new TextReader( );
System.out.print( "Enter first name: " );
firstName = keyboard.readWord( ); // Stop at 1st blank
System.out.print( "Enter address: " );
address = keyboard.readLine();
System.out.println( "Hello " + firstName
+ ", do you really live at " + address + "?" );
}
}
Sample Dialogs are on the next slide
3-21
Why does John live at
Rittenhouser?
Dialogue #1
Enter first name: John
Enter address: 1600 Pennsylvania Avenue
Hello John, do you really live at 1600 Pennsylvania Avenue?
Dialogue #2
Enter first name: John Rittenhouser
Enter address: 1600 Pennsylvania Avenue
Hello John, do you really live at Rittenhouser?
3-22
Assignment to Reference
Variables
 Primitive value assignment differs from references.
 Consider the following code:
int num1 = 456;
int num2 = 789;
num2 = num1;
num1 = 123;
System.out.println( "num1 is " + num1 );
System.out.println( "num2 is " + num2 );
Output:
num1 is 123
num2 is 456
 A change to one primitive does not affect the other.
Abstract notion of a List
3-23
 A list is:


a collection of elements (numbers, strings, accounts,
pictures,…)
ordered: there is a first, and a last element



lists can be empty – no elements
elements with a unique predecessor and successor
also known as a sequence
3-24
ArrayList
 Java has a class named ArrayList for storing a
collection of any class of objects.
 An ArrayList object stores a collection of any
objects.
 ArrayList is a realization of a list.

ArrayList elements aer indexed
 the first element is indexed by 0
 the last element is indexed by the ArrayList's size()-1
 use get and set
3-25
ArrayList
 The ArrayList class implements an expandable
list of elements.
 Next few slides use these methods (there are more):





add
get
set
size
toString
3-26
A few ArrayList messages
import java.util.ArrayList;
public class ShowArrayList
{
public static void main ( String[] args )
{
ArrayList list = new ArrayList( );
list.add( "first" );
list.add( "second" );
list.add( "third" );
list.add( "fourth" );
System.out.println( list.toString( ) );
Output so far
[first, second, third, fourth]
3-27
remove, size, get, set, toString
System.out.println("#elements: " + list.size( ));
System.out.println( list.toString( ) );
System.out.println( "[1]: " + list.get( 1 ) );
list.set( 1, "replacement" );
System.out.println( list.toString( ) );
Output
#elements: 4
[first, second, fourth]
[1]: second
What is this output at the final println?
3-28
Generic Collections
 A List can store any class of objects.
ArrayList accountList = new ArrayList( );
accountList.add( new BankAccount( "One", 111.11 ));
accountList.add( new BankAccount( "Two", 222.22 ));
accountList.add( new BankAccount( "Three", 333.33));
accountList.add( new BankAccount( "Four", 444.44 ));
System.out.println(accountList.toString());
Output
[One $111.11, Two $222.22, Three $333.33, Four $444.44]
3-29
Gregorian Calendar
import java.util.GregorianCalendar;
public class ShowTodaysDate
{
public static void main( String[] args )
{ // Assume this program ran on August 14, 2002
GregorianCalendar aDay = new GregorianCalendar();
int year = aDay.get( GregorianCalendar.YEAR );
int month= aDay.get( GregorianCalendar.MONTH );
int day = aDay.get( GregorianCalendar.DATE );
String date = year + "/" + month + "/" + day;
// Should Add 1 to month to get month as we know it
System.out.println( date );
}
}
3-30
Assigning Reference Values
 Assigning one reference value to another can have a
dramatically different result.
 Write the output from the following code:
BankAccount chris = new BankAccount( "Chris", 0.00 );
BankAccount kim = new BankAccount( "Kim", 100.00 );
kim = chris;
// The values (state) of the object were not assigned.
// Rather, the reference to chris was assigned to kim.
chris.deposit( 555.55 );
System.out.println("Kim's balance: " + kim.getBalance());
What is the Output?
// Was a message sent to kim?
Before the assignment of one reference value to a reference variable of the same type
chris
"Chris", 0.00
3-31
kim
"Kim", 100.00
After kim = chris
chris
kim
"Chris", 0.00
"Kim", 100.00
After chris.deposit( 555.55 );
chris
kim
"Chris", 555.55
lost forever
A Few Graphical Components
3-32
 A Graphical User Interface (GUI) presents a
graphical view of an application to users.
 To build a GUI application, you must:


make graphical components visible to the user
make sure the correct things happen when an event
occurs

user clicks button, moves mouse, presses enter key, ...
 Let's first consider some of Java's components:

windows, buttons, and text fields one line of editable text
3-33
Class in the swing package
 The javax.swing package has many components
that show themselves in a graphical manner
JFrame: window with title, border, menu, buttons
JButton: A component that can "clicked"
JLabel: A display area for a small amount of text
JTextField: Allows editing of a single line of text
3-34
Get a window to show itself
 To get these 4 classes, you could import all four as:
import
import
import
import
javax.swing.JFrame;
javax.swing.JButton;
javax.swing.JLabel;
javax.swing.JTextField;
or import all classes in the javax.swing package
import javax.swing.*;
 The following code gets a window to show itself:
// Construct a window with a title and show it
JFrame theWindow = new JFrame( "Graffiti" );
theWindow.show( );
3-35
Some messages JFrames know
 Set the size of the window with a setSize message.
theWindow.setSize( 220, 100 );


The first int is the width of the window in pixels
the second int is the height of the window in pixels
 You can also move upper left corner of the window
from with a setLocation message.
theWindow.setLocation( 150, 80 ); // 150 pixels right
theWindow.show( );
3-36
Building components
 So far we have an empty window.
 Let us add a button, a label, and an editable line.
 First construct three graphical components.
JButton clickMeButton =
new JButton( "Nobody is listening to me") ;
JLabel aLabel =
new JLabel( "Button above, text field below" );
JTextField textEditor =
new JTextField( "You can edit this text " );
 Next, add these objects to a window object.
3-37
Adding to the Content Pane
 In early versions of Java, you could add components
to the window (an instance of Frame, not JFrame).
 JFrame objects in Java 2 are more complex.
 Now you add components to the content pane.

JFrame objects store several objects including a
Container object known as the content pane
3-38
Add components to a window
 Get a reference to the Container part of a Jframe.
Container contentPane = theWindow.getContentPane( );
 Need something from abstract windowing toolkit:
import java.awt.Container and java.awt.BorderLayout
 Then add the previously constructed components to
one of the five areas of a JFrame
contentPane.add( clickMeButton, BorderLayout.NORTH );
contentPane.add( aLabel, BorderLayout.CENTER );
contentPane.add( textEditor, BorderLayout.SOUTH );
theWindow.show( );
3-39
The five areas of BorderLayout
 By default, JFrame objects have only five places
where you can add components. (adding a 2nd wipes out the 1st)



This can be modified to other layouts
Or add other containers that contain other containers
These five areas will do for now
3-40
BorderLayout
 By default, a JFrame object use the
BorderLayout layout manager to add graphical
components.
 Graphical user interfaces in all examples from
now on will use a different, more flexible, easier
to use layout manager.
 The Container's Layout manager can be changed
via a setLayout message.
3-41
GridLayout
 A GridLayout object can be constructed for
maximum programmer control by using the
following four int arguments:




1. The number of rows (5)
2. The number of columns (2)
3. Pixels between columns (8 below)
4. Pixels between rows (16 below)
GridLayout fiveByTwo = new GridLayout(5, 2, 8, 16);
3-42
setLayout
 Now send a setLayout message to the Container
object using this layout manager object as an
argument.
contentPane.setLayout( fiveByTwo );

demo