Download Java

Document related concepts
no text concepts found
Transcript
Java – Basic Introduction,
Classes and Objects
SEEM 3460
1
Java




A programming language specifies the words
and symbols that we can use to write a program
A programming language employs a set of rules
that dictate how the words and symbols can be
put together to form valid program statements
The Java programming language was created by
Sun Microsystems, Inc.
It was introduced in 1995 and it's popularity has
grown quickly since
SEEM 3460
2
Java Program Structure

In the Java programming language:





A program is made up of one or more classes
A class contains one or more methods
A method contains program statements
These terms will be explored in detail
throughout the course
A Java application always contains a method
called main
SEEM 3460
3
//************************************************
// Lincoln.java
//
// Demonstrates the basic structure of a Java application.
//************************************************
public class Lincoln
{
//----------------------------------------------------------------// Prints a presidential quote.
//----------------------------------------------------------------public static void main (String[] args)
{
System.out.println ("A quote by Abraham Lincoln:");
}
}
System.out.println ("Whatever you are, be a good one.");
SEEM 3460
4
Java Program Structure
//
comments about the class
public class MyProgram
{
class header
class body
Comments can be placed almost anywhere
}
5
Java Program Structure
//
comments about the class
public class MyProgram
{
//
comments about the method
public static void main (String[] args)
{
method body
method header
}
}
6
Comments


Comments in a program are called inline
documentation
They should be included to explain the purpose
of the program and describe processing steps

They do not affect how a program works

Java comments can take three forms:
// this comment runs to the end of the line
/*
this comment runs to the terminating
symbol, even across line breaks
/** this is a javadoc comment
*/
*/
7
Identifiers





Identifiers are the words a programmer uses in
a program
An identifier can be made up of letters, digits,
the underscore character ( _ ), and the dollar
sign
Identifiers cannot begin with a digit
Java is case sensitive - Total, total, and
TOTAL are different identifiers
By convention, programmers use different case
styles for different types of identifiers, such as

title case for class names - Lincoln

upper case for constants - MAXIMUM
8
Identifiers




Sometimes we choose identifiers ourselves
when writing a program (such as Lincoln)
Sometimes we are using another programmer's
code, so we use the identifiers that he or she
chose (such as println)
Often we use special identifiers called reserved
words that already have a predefined meaning
in the language
A reserved word cannot be used in any other
way
SEEM 3460
9
Reserved Words

The Java reserved words:
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
10
White Space





Spaces, blank lines, and tabs are called
white space
White space is used to separate words and
symbols in a program
Extra white space is ignored
A valid Java program can be formatted
many ways
Programs should be formatted to enhance
readability, using consistent indentation
11
Problem Solving




The key to designing a solution for a problem is
to break it down into manageable pieces
When writing software, we design separate
pieces that are responsible for certain parts of
the solution
An object-oriented approach lends itself to this
kind of solution decomposition
We will dissect our solutions into pieces called
objects and classes
SEEM 3460
12
Object-Oriented Programming





Java is an object-oriented programming
language
As the term implies, an object is a fundamental
entity in a Java program
Objects can be used effectively to represent
real-world entities
For instance, an object might represent a
particular employee in a company
Each employee object handles the processing
and data management related to that employee
SEEM 3460
13
Classes and Objects

An object is defined by a class

A class is the blueprint of an object




The class uses methods to define the
behaviors of the object
The class that contains the main method of a
Java program represents the entire program
A class represents a concept, and an object
represents the embodiment of that concept
Multiple objects can be created from the
same class
SEEM 3460
14
Classes and Objects
class
(the concept)
object
(the realization)
Bank
Account
John’s Bank Account
Balance: $5,257
Bill’s Bank Account
Balance: $1,245,069
Multiple objects
from the same class
Mary’s Bank Account
Balance: $16,833
SEEM 3460
15
Java Translation





The Java compiler translates Java source code
into a special representation called bytecode
Java bytecode is not the machine language for
any traditional CPU
Another software tool, called an interpreter,
translates bytecode into machine language and
executes it
Therefore the Java compiler is not tied to any
particular machine
Java is considered to be architecture-neutral
16
Java Translation
Java source
code
Java
compiler
Bytecode
interpreter
machine code
for target
machine 1
Java
bytecode
Bytecode
interpreter
machine code
for target
machine 2
17
Development Environments

There are many programs that support the
development of Java software, including:








Sun Java Development Kit (JDK)
Sun NetBeans
IBM Eclipse
Borland JBuilder
MetroWerks CodeWarrior
BlueJ
jGRASP
Though the details of these environments differ,
the basic compilation and execution process is
essentially the same
SEEM 3460
18
Compiling and Running Java on
Unix

We can compile a Java program under Unix by:
cuse93> javac Countdown.java


If the compilation is successful, a bytecode file
called Countdown.class will be generated.
To invoke Java bytecode interpreter, we can:
cuse93> java Countdown
Three… Two… One.. Zero… Liftoff!
Houston, we have a problem.
SEEM 3460
19
Variables


A variable is a name for a location in memory
A variable must be declared by specifying the
variable's name and the type of information that
it will hold
data type
variable name
int total;
int count, temp, result;
Multiple variables can be created in one declaration
SEEM 3460
20
Variable Initialization

A variable can be given an initial value in
the declaration
int sum = 0;
int base = 32, max = 149;
When a variable is referenced in a program, its current value is
used
SEEM 3460
21
Assignment


An assignment statement changes the value of
a variable
The assignment operator is the = sign
total = 55;
The expression on the right is evaluated and the result is
stored in the variable on the left
The value that was in total is overwritten
You can only assign a value to a variable that is consistent
with the variable's declared type
SEEM 3460
22
Constants




A constant is an identifier that is similar to a
variable except that it holds the same value
during its entire existence
As the name implies, it is constant, not variable
The compiler will issue an error if you try to
change the value of a constant
In Java, we use the final modifier to declare a
constant
final int MIN_HEIGHT = 69;
SEEM 3460
23
Constants


Constants are useful for three important reasons
First, they give meaning to otherwise unclear literal
values


Second, they facilitate program maintenance


For example, MAX_LOAD means more than the literal 250
If a constant is used in multiple places, its value need only
be updated in one place
Third, they formally establish that a value should not
change, avoiding inadvertent errors by other
programmers
SEEM 3460
24
Primitive Data

There are eight primitive data types in Java

Four of them represent integers:


Two of them represent floating point numbers:


float, double
One of them represents characters:


byte, short, int, long
char
And one of them represents boolean values:

boolean
SEEM 3460
25
Numeric Primitive Data

The difference between the various
numeric primitive types is their size, and
therefore the values they can store:
Type
Storage
Min Value
Max Value
byte
short
int
long
8 bits
16 bits
32 bits
64 bits
-128
-32,768
-2,147,483,648
< -9 x 1018
127
32,767
2,147,483,647
> 9 x 1018
float
double
32 bits
64 bits
+/- 3.4 x 1038 with 7 significant digits
+/- 1.7 x 10308 with 15 significant digits
SEEM 3460
26
Characters


A char variable stores a single character
Character literals are delimited by single
quotes:
'a'

'X'
'7'
'$'
','
'\n'
Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';

Note the distinction between a primitive character
variable, which holds only one character, and a String
object, which can hold multiple characters
SEEM 3460
27
Character Sets




A character set is an ordered list of characters,
with each character corresponding to a unique
number
A char variable in Java can store any character
from the Unicode character set
The Unicode character set uses sixteen bits per
character, allowing for 65,536 unique characters
It is an international character set, containing
symbols and characters from many world
languages
SEEM 3460
28
Characters


The ASCII character set is older and smaller
than Unicode, but is still quite popular
The ASCII characters are a subset of the
Unicode character set, including:
uppercase letters
lowercase letters
punctuation
digits
special symbols
control characters
A, B, C, …
a, b, c, …
period, semi-colon, …
0, 1, 2, …
&, |, \, …
carriage return, tab, ...
SEEM 3460
29
Boolean


A boolean value represents a true or false
condition
The reserved words true and false are the
only valid values for a boolean type
boolean done = false;

A boolean variable can also be used to
represent any two states, such as a light bulb
being on or off
SEEM 3460
30
Expression


An expression is a combination of one or more
operators and operands
Arithmetic expressions compute numeric results
and make use of the arithmetic operators:
Addition
Subtraction
Multiplication
Division
Remainder
+
*
/
%
If either or both operands used by an arithmetic operator are
floating point, then the result is a floating point
SEEM 3460
31
Division and Remainder

If both operands to the division operator (/) are
integers, the result is an integer (the fractional
part is discarded)
14 / 3
equals
4
8 / 12
equals
0
The remainder operator (%) returns the remainder after dividing
the second operand into the first
14 % 3
equals
2
8 % 12
equals
8
SEEM 3460
32
Operator Precedence

Operators can be combined into complex
expressions
result



=
total + count / max - offset;
Operators have a well-defined precedence which
determines the order in which they are
evaluated
Multiplication, division, and remainder are
evaluated prior to addition, subtraction, and
string concatenation
Arithmetic operators with the same precedence
are evaluated from left to right, but parentheses
can be used to force the evaluation order
SEEM 3460
33
Operator Precedence

What is the order of evaluation in the
following expressions?
a + b + c + d + e
1
2
3
a + b * c - d / e
4
3
1
4
2
a / (b + c) - d % e
2
1
4
3
a / (b * (c + (d - e)))
4
3
2
SEEM 3460
1
34
Expression Tree


The evaluation of a particular expression can be
shown using an expression tree
The operators lower in the tree have higher
precedence for that expression
+
a + (b – c) / d
/
a
b
SEEM 3460
d
c
35
Assignment Revisited

The assignment operator has a lower
precedence than the arithmetic operators
First the expression on the right hand
side of the = operator is evaluated
answer
=
4
sum / 4 + MAX * lowest;
1
3
2
Then the result is stored in the
variable on the left hand side
SEEM 3460
36
Assignment Revisited

The right and left hand sides of an assignment
statement can contain the same variable
First, one is added to the
original value of count
count
=
count + 1;
Then the result is stored back into count
(overwriting the original value)
SEEM 3460
37
Increment and Decrement




The increment and decrement operators use
only one operand
The increment operator (++) adds one to its
operand
The decrement operator (--) subtracts one
from its operand
The statement
count++;
is functionally equivalent to
count = count + 1;
38
Increment and Decrement

The increment and decrement operators can be
applied in postfix form:
count++

or prefix form:
++count


When used as part of a larger expression, the
two forms can have different effects
Because of their subtleties, the increment and
decrement operators should be used with care
39
Increment and Decrement

Suppose count has a value of 15

Consider the following statement:
total = count++


After the assignment, total has a value of 15,
whereas count has a value of 16
Consider the following statement:
total = ++count

Both total and count have a value of 16
40
Assignment Operators



Often we perform an operation on a variable,
and then store the result back into that variable
Java provides assignment operators to simplify
that process
For example, the statement
num += count;
is equivalent to
num = num + count;
41
Assignment Operators

There are many assignment operators in
Java, including the following:
Operator
+=
-=
*=
/=
%=
Example
x
x
x
x
x
+=
-=
*=
/=
%=
y
y
y
y
y
Equivalent To
x
x
x
x
x
=
=
=
=
=
x
x
x
x
x
+
*
/
%
y
y
y
y
y
42
Assignment Operators



The right hand side of an assignment operator
can be a complex expression
The entire right-hand expression is evaluated
first, then the result is combined with the
original variable
Therefore
result /= (total-MIN) % num;
is equivalent to
result = result / ((total-MIN) % num);
43
Assignment Operators



The behavior of some assignment operators
depends on the types of the operands
If the operands to the += operator are strings,
the assignment operator performs string
concatenation
The behavior of an assignment operator (+=) is
always consistent with the behavior of the
corresponding operator (+)
SEEM 3460
44
String Concatenation

The string concatenation operator (+) is used to
append one string to the end of another
"Peanut butter " + "and jelly"



It can also be used to append a number to a
string
A string literal cannot be broken across two
lines in a program
See Facts.java

The println method can print a character string
SEEM 3460
45
//********************************************************
// Facts.java
//
// Demonstrates the use of the string concatenation operator and the
// automatic conversion of an integer to a string.
//*******************************************************
public class Facts
{
//----------------------------------------------------------------// Prints various facts.
//----------------------------------------------------------------public static void main (String[] args)
{
// Strings can be concatenated into one long string
System.out.println ("We present the following facts for your "
+ "extracurricular edification:");
System.out.println ();
// A string can contain numeric digits
System.out.println ("Letters in the Hawaiian alphabet: 12");
// A numeric value can be concatenated to a string
System.out.println ("Dialing code for Antarctica: " + 672);
System.out.println ("Year in which Leonardo da Vinci invented "
+ "the parachute: " + 1515);
System.out.println ("Speed of ketchup: " + 40 + " km per year");
}
}
SEEM 3460
46
String Concatenation





The + operator is also used for arithmetic addition
The function that it performs depends on the type of the
information on which it operates
If both operands are strings, or if one is a string and one
is a number, it performs string concatenation
If both operands are numeric, it adds them
The + operator is evaluated left to right, but
parentheses can be used to force the order
SEEM 3460
47
Escape Sequences


What if we wanted to print a the quote character?
The following line would confuse the compiler because it
would interpret the second quote as the end of the string
System.out.println ("I said "Hello" to you.");


An escape sequence is a series of characters that
represents a special character
An escape sequence begins with a backslash character
(\)
System.out.println ("I said \"Hello\" to you.");
SEEM 3460
48
Escape Sequences

Some Java escape sequences:
Escape Sequence
\b
\t
\n
\r
\"
\'
\\
Meaning
backspace
tab
newline
carriage return
double quote
single quote
backslash
SEEM 3460
49
Data Conversion



Sometimes it is convenient to convert
data from one type to another
For example, in a particular situation we
may want to treat an integer as a floating
point value
These conversions do not change the
type of a variable or the value that's
stored in it – they only convert a value as
part of a computation
SEEM 3460
50
Data Conversion




Conversions must be handled carefully to avoid losing
information
Widening conversions are safest because they tend to go
from a small data type to a larger one (such as a short
to an int)
Narrowing conversions can lose information because they
tend to go from a large data type to a smaller one (such
as an int to a short)
In Java, data conversions can occur in three ways:



assignment conversion
promotion
casting
SEEM 3460
51
Assignment Conversion


Assignment conversion occurs when a value of
one type is assigned to a variable of another
If money is a float variable and dollars is an
int variable, the following assignment converts
the value in dollars to a float
money = dollars


Only widening conversions can happen via
assignment
Note that the value or type of dollars did not
change
SEEM 3460
52
Data Conversion


Promotion happens automatically when
operators in expressions convert their operands
For example, if sum is a float and count is an
int, the value of count is converted to a
floating point value to perform the following
calculation:
result = sum / count;
SEEM 3460
53
Casting




Casting is the most powerful, and dangerous,
technique for conversion
Both widening and narrowing conversions can
be accomplished by explicitly casting a value
To cast, the type is put in parentheses in
front of the value being converted
For example, if total and count are integers,
but we want a floating point result when
dividing them, we can cast total:
result = (float) total / count;
SEEM 3460
54
Character Strings


A string of characters can be represented as a
string literal by putting double quotes around
the text:
Examples:
"This is a string literal."
"123 Main Street"
"X"


Every character string is an object in Java,
defined by the String class
Every string literal represents a String object
SEEM 3460
55
The println Method


In the previous Lincoln program, we invoked
the println method to print a character string
System.out is a built-in object representing a
destination (the monitor screen) to which we
can send output
System.out.println ("Whatever you are, be a good one.");
object
method
name
information provided to the method
(parameters)
SEEM 3460
56
The print Method




The System.out object provides another service
as well
The print method is similar to the println
method, except that it does not advance to the
next line
Therefore anything printed after a print
statement will appear on the same line
See Countdown.java
SEEM 3460
57
//************************************************
// Countdown.java
//
// Demonstrates the difference between print and println.
//************************************************
public class Countdown
{
//----------------------------------------------------------------// Prints two lines of output representing a rocket countdown.
//----------------------------------------------------------------public static void main (String[] args)
{
System.out.print ("Three... ");
System.out.print ("Two... ");
System.out.print ("One... ");
System.out.print ("Zero... ");
System.out.println ("Liftoff!"); // appears on first output line
}
}
System.out.println ("Houston, we have a problem.");
SEEM 3460
58
Interactive Programs




Programs generally need input on which to
operate
The built-in Scanner class provides convenient
methods for reading input values of various
types
A Scanner object (called scan) can be set up to
read input from various sources, including the
user typing values on the keyboard
Keyboard input is represented by the System.in
object
SEEM 3460
59
Reading Input

The following line creates a Scanner object,
called scan, that reads from the keyboard:
Scanner scan = new Scanner (System.in);


The new operator creates the Scanner object,
called scan
Once created, the Scanner object (i.e. scan)
can be used to invoke various input methods,
such as nextLine():
answer = scan.nextLine();
SEEM 3460
60
Reading Input

The Scanner class is part of the
java.util class library, and must be
imported into a program to be used



See Echo.java
The nextLine method reads all of the
input until the end of the line is found
The details of object creation and class
libraries are discussed later
SEEM 3460
61
//*************************************************************
// Echo.java
//
// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
//*************************************************************
import java.util.Scanner;
public class Echo
{
//----------------------------------------------------------------// Reads a character string from the user and prints it.
//----------------------------------------------------------------public static void main (String[] args)
{
String message;
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a line of text:");
message = scan.nextLine();
}
}
System.out.println ("You entered: \"" + message + "\"");
SEEM 3460
62
Echo.java - Sample Execution

The following is a sample execution of
Echo.class
cuse93> java Echo
Enter a line of text:
This is a line
You entered: “This is a line”
SEEM 3460
63
Input Tokens





Unless specified otherwise, white space is used
to separate the elements (called tokens) of the
input
White space includes space characters, tabs,
new line characters
The next method of the Scanner class reads the
next input token and returns it as a string
Methods such as nextInt and nextDouble read
data of particular types
See GasMileage.java
SEEM 3460
64
//*************************************************************
// GasMileage.java
//
// Demonstrates the use of the Scanner class to read numeric data.
//*************************************************************
import java.util.Scanner;
public class GasMileage {
//----------------------------------------------------------------// Calculates fuel efficiency based on values entered by the
// user.
//----------------------------------------------------------------public static void main (String[] args) {
int miles;
double gallons, mpg;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the number of miles: ");
miles = scan.nextInt();
System.out.print ("Enter the gallons of fuel used: ");
gallons = scan.nextDouble();
mpg = miles / gallons;
}
}
System.out.println ("Miles Per Gallon: " + mpg);
SEEM 3460
65
GasMileage.java - Sample
Execution

The following is a sample execution of
GasMileage.class
cuse93> java GasMileage
Enter the number of miles: 34
Enter the gallons of fuel used: 17
Miles Per Gallon: 2.0
SEEM 3460
66
Writing Classes



Now we will begin to design programs
that rely on classes that we write
ourselves
The class that contains the main
method is just the starting point of a
program
True object-oriented programming is
based on defining classes that
represent objects with well-defined
characteristics and functionality
SEEM 3460
67
Designing Classes and Objects

An object has state and behavior

Consider a six-sided die (singular of dice)


It’s state can be defined as which face is showing

It’s primary behavior is that it can be rolled
We can represent a die in software by
designing a class called Die that models this
state and behavior


The class serves as the blueprint for a die object
We can then instantiate as many die objects
as we need for any particular program
SEEM 3460
68
Classes

A class can contain data declarations and
method declarations
int size, weight;
char category;
Data declarations
Method declarations
SEEM 3460
69
Classes




The values of the data define the state of an
object created from the class
The functionality of the methods define the
behaviors of the object
For our Die class, we might declare an integer
that represents the current value showing on
the face
One of the methods would “roll” the die by
setting that value to a random number between
one and six
SEEM 3460
70
Classes



In general, a class share some similarities with
structures in C
Recall that a structure in C is a user-defined
data type composed of some data fields and
each field belongs to a certain data type or
another structure type
A class is also composed of some data fields. In
addition to it, a class is also associated with
some methods
SEEM 3460
71
General
Design
of
Objects
and
Classes
• In general, we should first declare an object reference
• Then, we allocate memory for the object
AClass obj1;
obj1 = new AClass();
obj1

The first line declares an object reference
obj1 belonging to a class called AClass

The second line uses the new operator to
allocate some memory for an object (under
the class AClass) and lets obj1 points to it

The second line also invokes the AClass
constructor, if exists, to initialize the data in
the object
Data fields for obj1
SEEM 3460
72
General Design of Objects and Classes



Similar to structures in C, one can access the data fields of
an object via the dot operator
For example, suppose in the class AClass, there are some
data fields declared such as field1 and field2.
Then, we can access field1 in obj1 via:
obj1.field1 = 100;



We can process an object by a method specified in the corresponding
class via dot operator
Suppose in the class AClass, there are some methods declared such
as method1 and method2
Then we can process the object obj1 by method1 via:
a_value = obj1.method1();
SEEM 3460
73
Creating Objects – Another Example


A variable holds either a primitive type or a reference to
an object
A class name can be used as a type to declare an object
reference variable
String title;

An object reference variable holds the address of an
object

The object itself must be created separately

Generally, we use the new operator to create an object
title = new String ("Java Software Solutions");
This calls the String constructor, which is
a special method that sets up the object
SEEM 3460
74
Creating Objects - Instantiation


Creating an object is called instantiation
An object is an instance of a particular
class
SEEM 3460
75
Invoking Methods

We've seen that once an object has been
instantiated, we can use the dot operator to
invoke its methods
count = title.length()


A method may return a value, which can be
used in an assignment or expression
A method invocation can be thought of as
asking an object to perform a service
SEEM 3460
76
Object References



Note that a primitive variable contains the value
itself, but an object variable contains the
address of the object
An object reference can be thought of as a
pointer to the location of the object
Rather than dealing with arbitrary addresses,
we often depict a reference graphically
num1 38
title1
"Steve Jobs"
SEEM 3460
77
A Complete Example of Classes and Objects

Return to the example of our Die class



For our Die class, we might declare an integer that
represents the current value showing on the face
One of the methods would “roll” the die by setting
that value to a random number between one and six
We’ll want to design the Die class with other
data and methods to make it a versatile and
reusable resource
See RollingDice.java
See Die.java
SEEM 3460
78
//*************************************************************
// RollingDice.java
//
// Demonstrates the creation and use of a user-defined class.
//*************************************************************
public class RollingDice
{
//----------------------------------------------------------------// Creates two Die objects and rolls them several times.
//----------------------------------------------------------------public static void main (String[] args)
{
Die die1, die2;
int sum;
die1 = new Die();
die2 = new Die();
die1.roll();
die2.roll();
System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
SEEM 3460
79
die1.roll();
die2.setFaceValue(4);
System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
sum = die1.getFaceValue() + die2.getFaceValue();
System.out.println ("Sum: " + sum);
}
}
sum = die1.roll() + die2.roll();
System.out.println ("Die One: " + die1 + ", Die Two: " + die2);
System.out.println ("New sum: " + sum);
SEEM 3460
80
//*************************************************************
// Die.java
//
// Represents one die (singular of dice) with faces showing values
// between 1 and 6.
//*************************************************************
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
//----------------------------------------------------------------// Constructor: Sets the initial face value.
//----------------------------------------------------------------public Die()
{
faceValue = 1;
}
SEEM 3460
81
//----------------------------------------------------------------// Rolls the die and returns the result.
//----------------------------------------------------------------public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
//----------------------------------------------------------------// Face value mutator.
//----------------------------------------------------------------public void setFaceValue (int value)
{
faceValue = value;
}
//----------------------------------------------------------------// Face value accessor.
//----------------------------------------------------------------public int getFaceValue()
{
return faceValue;
}
SEEM 3460
82
//----------------------------------------------------------------// Returns a string representation of this die.
//----------------------------------------------------------------public String toString()
{
String result = Integer.toString(faceValue);
}
}
return result;
SEEM 3460
83
The Die Class

The Die class contains two data values




a constant MAX that represents the maximum face
value
an integer faceValue that represents the current face
value
The roll method uses the random method of the
Math class to determine a new face value
There are also methods to explicitly set and
retrieve the current face value at any time
SEEM 3460
84
Data Scope





The scope of data is the area in a program in which that
data can be referenced (used)
Data declared at the class level can be referenced by all
methods in that class
Data declared within a method can be used only in that
method
Data declared within a method is called local data
In the Die class, the variable result is declared inside the
toString method -- it is local to that method and cannot
be referenced anywhere else
SEEM 3460
85
Instance Data





The faceValue variable in the Die class is called
instance data because each instance (object) that is
created has its own version of it
A class declares the type of the data, but it does not
reserve any memory space for it
Every time a Die object is created, a new faceValue
variable is created as well
The objects of a class share the method definitions,
but each object has its own data space
That's the only way two objects can have different
states
SEEM 3460
86
Instance Data

We can depict the two Die objects from the
RollingDice program as follows:
die1
faceValue
5
die2
faceValue
2
Each object maintains its own faceValue
variable, and thus its own state
SEEM 3460
87
The toString Method



All classes that represent objects should define
a toString method
The toString method returns a character string
that represents the object in some way
It is called automatically when an object is
concatenated to a string or when it is passed
to the println method
SEEM 3460
88
Constructors




A constructor is a special method that is used
to set up an object when it is initially created
A constructor has the same name as the
class and it has no return data type
The Die constructor is used to set the initial
face value of each new die object to one
We examine constructors in more detail later
SEEM 3460
89
RollingDice.java - Compilation


Assume that both RollingDice.java and Die.java are stored
under the same directory in an Unix account
To compile under Unix platform, we can simply compile the
RollingDice.java:
cuse93> javac RollingDice.java




The compiler will first compile RollingDice.java. When it finds out
that it needs to make use of the class Die.java. It will
automatically compile Die.java
If the compilation is successful, you can find two bytecodes,
namely, RollingDice.class and Die.class
If there is compilation error, the error message will be displayed
on the terminal.
If you wish to make the error message be displayed screen by
screen, you can compile in the following way:
cuse93> javac RollingDice.java |& more
SEEM 3460
90
RollingDice.java - Sample
Execution

The following is a sample execution of
RollingDice.class
cuse93> java RollingDice
Die One: 6, Die Two: 1
Die One: 4, Die Two: 4
Sum: 8
Die One: 3, Die Two: 2
New sum: 5
SEEM 3460
91
Assignment Revisited



In traditional programming language (non object-oriented)
such as C, we can declare variables and conduct assignment
on variables
The act of assignment takes a copy of a value and stores it
in a variable
For example, consider the integer variables:
int num1, num2;
num2 = num1;
num1 38
num1 38
Before:
num2
After:
96
SEEM 3460
num2
38
92
Reference Assignment

For object references, assignment copies the address

For example, suppose that name1 and name2 are two object
references
Before:
title1
"Steve Jobs"
title2
"Steve Wozniak"
title2 = title1;
title1
After:
"Steve Jobs"
title2
SEEM 3460
93
Aliases




Two or more references that refer to the same
object are called aliases of each other
That creates an interesting situation: one object
can be accessed using multiple reference
variables
Aliases can be useful, but should be managed
carefully
Changing an object through one reference
changes it for all of its aliases, because there is
really only one object
SEEM 3460
94
Class Libraries





A class library is a collection of classes that we can use
when developing programs
The Java standard class library is part of any Java
development environment
Its classes are not part of the Java language per se, but
we rely on them heavily
Various classes we've already used (System , Scanner,
String) are part of the Java standard class library
Other class libraries can be obtained through third party
vendors, or you can create them yourself
SEEM 3460
95
Packages


The classes of the Java standard class library
are organized into packages
Some of the packages in the standard class
library are:
Package
Purpose
java.lang
java.applet
java.awt
javax.swing
java.net
java.util
javax.xml.parsers
General support
Creating applets for the web
Graphics and graphical user interfaces
Additional graphics capabilities
Network communication
Utilities
XML document processing
SEEM 3460
96
The import Declaration

When you want to use a class from a package,
you could use its fully qualified name
java.util.Scanner

Or you can import the class, and then use just
the class name
import java.util.Scanner;

To import all classes in a particular package,
you can use the * wildcard character
import java.util.*;
SEEM 3460
97
The import Declaration


All classes of the java.lang package are
imported automatically into all programs
It's as if all programs contain the following
line:
import java.lang.*;


That's why we didn't have to import the
System or String classes explicitly in earlier
programs
The Scanner class, on the other hand, is part
of the java.util package, and therefore must
be imported
SEEM 3460
98
The Random Class



The Random class is part of the java.util
package
It provides methods that generate
pseudorandom numbers
A Random object performs complicated
calculations based on a seed value to produce a
stream of seemingly random values
See RandomNumbers.java
SEEM 3460
99
//*************************************************************
// RandomNumbers.java
//
// Demonstrates the creation of pseudo-random numbers using the
// Random class.
//*************************************************************
import java.util.Random;
public class RandomNumbers
{
//----------------------------------------------------------------// Generates random numbers in various ranges.
//----------------------------------------------------------------public static void main (String[] args)
{
Random generator = new Random();
int num1;
float num2;
num1 = generator.nextInt();
System.out.println ("A random integer: " + num1);
SEEM 3460
100
num1 = generator.nextInt(10);
System.out.println ("From 0 to 9: " + num1);
num1 = generator.nextInt(10) + 1;
System.out.println ("From 1 to 10: " + num1);
num1 = generator.nextInt(15) + 20;
System.out.println ("From 20 to 34: " + num1);
num1 = generator.nextInt(20) - 10;
System.out.println ("From -10 to 9: " + num1);
num2 = generator.nextFloat();
System.out.println ("A random float (between 0-1): " + num2);
}
}
num2 = generator.nextFloat() * 6; // 0.0 to 5.999999
num1 = (int)num2 + 1;
System.out.println ("From 1 to 6: " + num1);
SEEM 3460
101
RandomNumbers.java - Sample Execution

The following is a sample execution of
RandomNumbers.class
cuse93> java RandomNumbers
A random integer: -1709988757
From 0 to 9: 2
From 1 to 10: 9
From 20 to 34: 31
From -10 to 9: 1
A random float (between 0-1): 0.7517807
From 1 to 6: 2
SEEM 3460
102
Encapsulation

We can take one of two views of an object:




internal - the details of the variables and methods of
the class that defines it
external - the services that an object provides and
how the object interacts with the rest of the system
From the external view, an object is an
encapsulated entity, providing a set of specific
services
These services define the interface to the object
SEEM 3460
103
Encapsulation


An encapsulated object can be thought of as a
black box -- its inner workings are hidden from
the client
The client invokes the interface methods of the
object, which manages the instance data
Client
Methods
Data
SEEM 3460
104
Method Declarations





Let’s now examine method declarations in more detail
A method declaration specifies the code that will be
executed when the method is invoked (called)
When a method is invoked, the flow of control jumps
to the method and executes its code
When complete, the flow returns to the place where
the method was called and continues
The invocation may or may not return a value,
depending on how the method is defined
SEEM 3460
105
Method Control Flow

If the called method is in the same class, only
the method name is needed
compute
myMethod
myMethod();
SEEM 3460
106
Method Control Flow

The called method is often part of another class
or object
main
obj.doIt();
doIt
helpMe
helpMe();
SEEM 3460
107
Method Header

A method declaration begins with a method
header
char calc (int num1, int num2, String message)
method
name
return
type
parameter list
The parameter list specifies the type
and name of each parameter
The name of a parameter in the method
declaration is called a formal parameter
SEEM 3460
108
Method Body

The method header is followed by the method
body
char calc (int num1, int num2, String message)
{
}
int sum = num1 + num2;
char result = message.charAt (sum);
return result;
sum and result
are local data
The return expression
must be consistent with
the return type
SEEM 3460
They are created
each time the
method is called,
and are destroyed
when it finishes
109
executing
The return Statement



The return type of a method indicates the type
of value that the method sends back to the
calling location
A method that does not return a value has a
void return type
A return statement specifies the value that will
be returned
return expression;

Its expression must conform to the return type
SEEM 3460
110
Parameters

When a method is called, the actual
parameters in the invocation are copied into
the formal parameters in the method header
ch = obj.calc (25, count, "Hello");
char calc (int num1, int num2, String message)
{
}
int sum = num1 + num2;
char result = message.charAt (sum);
return result;
SEEM 3460
111
Local Data




As we’ve seen, local variables can be declared
inside a method
The formal parameters of a method create
automatic local variables when the method is
invoked
When the method finishes, all local variables are
destroyed (including the formal parameters)
Keep in mind that instance variables, declared
at the class level, exists as long as the object
exists
SEEM 3460
112
Bank Account Example




Let’s look at another example that
demonstrates the implementation details of
classes and methods
We’ll represent a bank account by a class
named Account
It’s state can include the account number, the
current balance, and the name of the owner
An account’s behaviors (or services) include
deposits and withdrawals, and adding interest
SEEM 3460
113
Driver Programs



A driver program drives the use of other, more
interesting parts of a program
Driver programs are often used to test other
parts of the software
The Transactions class contains a main method
that drives the use of the Account class,
exercising its services
See Transactions.java
See Account.java
SEEM 3460
114
//*************************************************************
// Transactions.java
//
// Demonstrates the creation and use of multiple Account objects.
//*************************************************************
public class Transactions
{
//----------------------------------------------------------------// Creates some bank accounts and requests various services.
//----------------------------------------------------------------public static void main (String[] args)
{
Account acct1 = new Account ("Ted Murphy", 72354, 102.56);
Account acct2 = new Account ("Jane Smith", 69713, 40.00);
Account acct3 = new Account ("Edward Demsey", 93757, 759.32);
acct1.deposit (25.85);
double smithBalance = acct2.deposit (500.00);
System.out.println ("Smith balance after deposit: " +
smithBalance);
SEEM 3460
115
System.out.println ("Smith balance after withdrawal: " +
acct2.withdraw (430.75, 1.50));
acct1.addInterest();
acct2.addInterest();
acct3.addInterest();
}
}
System.out.println
System.out.println
System.out.println
System.out.println
();
(acct1);
(acct2);
(acct3);
SEEM 3460
116
//*************************************************************
// Account.java
//
// Represents a bank account with basic services such as deposit
// and withdraw.
//*************************************************************
import java.text.NumberFormat;
public class Account
{
private final double RATE = 0.035; // interest rate of 3.5%
private long acctNumber;
private double balance;
private String name;
//----------------------------------------------------------------// Sets up the account by defining its owner, account number,
// and initial balance.
//----------------------------------------------------------------public Account (String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
SEEM 3460
}
117
//----------------------------------------------------------------// Deposits the specified amount into the account. Returns the
// new balance.
//----------------------------------------------------------------public double deposit (double amount)
{
balance = balance + amount;
}
return balance;
//----------------------------------------------------------------// Withdraws the specified amount from the account and applies
// the fee. Returns the new balance.
//----------------------------------------------------------------public double withdraw (double amount, double fee)
{
balance = balance - amount - fee;
}
return balance;
SEEM 3460
118
//----------------------------------------------------------------// Adds interest to the account and returns the new balance.
//----------------------------------------------------------------public double addInterest ()
{
balance += (balance * RATE);
return balance;
}
//----------------------------------------------------------------// Returns the current balance of the account.
//----------------------------------------------------------------public double getBalance ()
{
return balance;
}
//----------------------------------------------------------------// Returns a one-line description of the account as a string.
//----------------------------------------------------------------public String toString ()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
}
}
return (acctNumber + "\t" + name + "\t" + fmt.format(balance));
SEEM 3460
119
Transactions.java - Sample
Execution

The following is a sample execution of
Transactions.class
cuse93> java Transactions
Smith balance after deposit: 540.0
Smith balance after withdrawal: 107.75
72354
69713
93757
Ted Murphy
$132.90
Jane Smith
$111.52
Edward Demsey $785.90
SEEM 3460
120
Bank Account Example
acct1
acctNumber 72354
balance 102.56
name
acct2
“Ted Murphy”
acctNumber 69713
balance 40.00
name
SEEM 3460
“Jane Smith”
121
Constructors Revisited




Note that a constructor has no return type
specified in the method header, not even void
A common error is to put a return type on a
constructor, which makes it a “regular” method
that happens to have the same name as the
class
The programmer does not have to define a
constructor for a class
Each class has a default constructor that
accepts no parameters
SEEM 3460
122