Java – Basic Introduction, Classes and Objectsseem3460/lecture/Java-basic-intro-class-obj… ·...
Transcript of Java – Basic Introduction, Classes and Objectsseem3460/lecture/Java-basic-intro-class-obj… ·...
SEEM 3460 1
Java – Basic Introduction, Classes and Objects
SEEM 3460 2
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
Java
SEEM 3460 3
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
Java Program Structure
SEEM 3460 4
//************************************************// 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.");}
}
5
Java Program Structure
public class MyProgram
{
}
// comments about the class
class header
class body
Comments can be placed almost anywhere
6
Java Program Structure
public class MyProgram
{
}
// comments about the class
public static void main (String[] args)
{
}
// comments about the method
method headermethod body
7
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 terminatingsymbol, even across line breaks */
/** this is a javadoc comment */
8
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, andTOTAL 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
SEEM 3460 9
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
Identifiers
10
Reserved Words
The Java reserved words:
abstractassertbooleanbreakbytecasecatchcharclassconstcontinuedefaultdodouble
elseenumextendsfalsefinalfinallyfloatforgotoifimplementsimportinstanceofint
interfacelongnativenewnullpackageprivateprotectedpublicreturnshortstaticstrictfpsuper
switchsynchronizedthisthrowthrowstransienttruetryvoidvolatilewhile
11
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
SEEM 3460 12
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
Problem Solving
SEEM 3460 13
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
Object-Oriented Programming
SEEM 3460 14
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 15
Bank Account
class(the concept)
John’s Bank AccountBalance: $5,257
object(the realization)
Bill’s Bank AccountBalance: $1,245,069
Mary’s Bank AccountBalance: $16,833
Multiple objectsfrom the same class
Classes and Objects
16
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
17
Java Translation
Java sourcecode
Javabytecode
Javacompiler
Bytecodeinterpreter
machine codefor targetmachine 1
Bytecodeinterpreter
machine codefor targetmachine 2
SEEM 3460 18
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
Development Environments
SEEM 3460 19
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 CountdownThree… Two… One.. Zero… Liftoff!Houston, we have a problem.
SEEM 3460 20
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
int total;
int count, temp, result;
Multiple variables can be created in one declaration
data type variable name
SEEM 3460 21
A variable can be given an initial value in the declaration
When a variable is referenced in a program, its current value is used
int sum = 0;int base = 32, max = 149;
Variable Initialization
SEEM 3460 22
Assignment
An assignment statement changes the value of a variable
The assignment operator is the = sign
total = 55;
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
The expression on the right is evaluated and the result is stored in the variable on the left
SEEM 3460 23
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;
Constants
SEEM 3460 24
Constants are useful for three important reasons
First, they give meaning to otherwise unclear literal values
For example, MAX_LOAD means more than the literal 250
Second, they facilitate program maintenance
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
Constants
SEEM 3460 25
There are eight primitive data types in Java
Four of them represent integers: byte, short, int, long
Two of them represent floating point numbers: float, double
One of them represents characters: char
And one of them represents boolean values: boolean
Primitive Data
SEEM 3460 26
The difference between the various numeric primitive types is their size, and therefore the values they can store:
Type
byteshortintlong
floatdouble
Storage
8 bits16 bits32 bits64 bits
32 bits64 bits
Min Value
-128-32,768-2,147,483,648< -9 x 1018
+/- 3.4 x 1038 with 7 significant digits+/- 1.7 x 10308 with 15 significant digits
Max Value
12732,7672,147,483,647> 9 x 1018
Numeric Primitive Data
SEEM 3460 27
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 Stringobject, which can hold multiple characters
SEEM 3460 28
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
Character Sets
SEEM 3460 29
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 letterslowercase letterspunctuationdigitsspecial symbolscontrol characters
A, B, C, …a, b, c, …period, semi-colon, …0, 1, 2, …&, |, \, …carriage return, tab, ...
SEEM 3460 30
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 31
An expression is a combination of one or more operators and operands
Arithmetic expressions compute numeric results and make use of the arithmetic operators:
If either or both operands used by an arithmetic operator are floating point, then the result is a floating point
AdditionSubtractionMultiplicationDivisionRemainder
+-*/%
Expression
SEEM 3460 32
If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded)
The remainder operator (%) returns the remainder after dividing the second operand into the first
14 / 3 equals
8 / 12 equals
4
0
14 % 3 equals
8 % 12 equals
2
8
Division and Remainder
SEEM 3460 33
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
Operator Precedence
SEEM 3460 34
What is the order of evaluation in the following expressions?
a + b + c + d + e1 432
a + b * c - d / e3 241
a / (b + c) - d % e2 341
a / (b * (c + (d - e)))4 123
Operator Precedence
SEEM 3460 35
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) / da
+
/
- d
b c
Expression Tree
SEEM 3460 36
The assignment operator has a lower precedence than the arithmetic operators
First the expression on the right handside of the = operator is evaluated
Then the result is stored in thevariable on the left hand side
answer = sum / 4 + MAX * lowest;
14 3 2
Assignment Revisited
SEEM 3460 37
The right and left hand sides of an assignment statement can contain the same variable
First, one is added to theoriginal value of count
Then the result is stored back into count(overwriting the original value)
count = count + 1;
Assignment Revisited
38
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 tocount = count + 1;
39
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
40
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
41
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;
42
Assignment Operators
There are many assignment operators in Java, including the following:
Operator
+=-=*=/=%=
Example
x += yx -= yx *= yx /= yx %= y
Equivalent To
x = x + yx = x - yx = x * yx = x / yx = x % y
43
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
Thereforeresult /= (total-MIN) % num;
is equivalent toresult = result / ((total-MIN) % num);
SEEM 3460 44
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 (+)
Assignment Operators
SEEM 3460 45
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 46
//********************************************************// 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 stringSystem.out.println ("We present the following facts for your "
+ "extracurricular edification:");System.out.println ();// A string can contain numeric digitsSystem.out.println ("Letters in the Hawaiian alphabet: 12");// A numeric value can be concatenated to a stringSystem.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 47
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 48
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 49
Escape Sequences
Some Java escape sequences:Escape Sequence
\b\t\n\r\"\'\\
Meaning
backspacetabnewlinecarriage returndouble quotesingle quotebackslash
SEEM 3460 50
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 51
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 shortto 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 52
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 53
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 54
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 55
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
Character Strings
SEEM 3460 56
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 methodname information provided to the method
(parameters)
The println Method
SEEM 3460 57
The print Method
The System.out object provides another service as well
The print method is similar to the printlnmethod, except that it does not advance to the next line
Therefore anything printed after a printstatement will appear on the same line
See Countdown.java
SEEM 3460 58
//************************************************// 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 59
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.inobject
SEEM 3460 60
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 61
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 62
//*************************************************************// 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 63
Echo.java - Sample Execution
The following is a sample execution of Echo.classcuse93> java EchoEnter a line of text:This is a lineYou entered: “This is a line”
SEEM 3460 64
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 65
//*************************************************************// 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 66
GasMileage.java - Sample Execution
The following is a sample execution of GasMileage.classcuse93> java GasMileageEnter the number of miles: 34Enter the gallons of fuel used: 17Miles Per Gallon: 2.0
SEEM 3460 67SEEM 3460 67
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 68SEEM 3460 68
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 69SEEM 3460 69
Classes A class can contain data declarations and
method declarations
int size, weight;char category;
Data declarations
Method declarations
SEEM 3460 70SEEM 3460 70
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 71SEEM 3460 71
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
General Design of Objects and Classes
SEEM 3460 72
• In general, we should first declare an object reference
• Then, we allocate memory for the object
SEEM 3460 72
AClass obj1;
obj1 = new AClass();
The first line declares an object reference obj1 belonging to a class called AClass
Data fields for obj1obj1
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
SEEM 3460 73SEEM 3460 73
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:
General Design of Objects and Classes
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 74SEEM 3460 74
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 isa special method that sets up the object
SEEM 3460 75SEEM 3460 75
Creating Objects - Instantiation Creating an object is called instantiation
An object is an instance of a particular class
SEEM 3460 76SEEM 3460 76
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 7777
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
"Steve Jobs"title1
num1 38
SEEM 3460 78SEEM 3460 78
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
A Complete Example of Classes and Objects
SEEM 3460 79SEEM 3460 79
//*************************************************************// 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 80SEEM 3460 80
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 81SEEM 3460 81
//*************************************************************// 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 82SEEM 3460 82
//-----------------------------------------------------------------// 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 83SEEM 3460 83
//-----------------------------------------------------------------// Returns a string representation of this die.//-----------------------------------------------------------------public String toString(){
String result = Integer.toString(faceValue);
return result;}
}
SEEM 3460 84SEEM 3460 84
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 85SEEM 3460 85
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 86SEEM 3460 86
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 faceValuevariable 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 87SEEM 3460 87
Instance Data We can depict the two Die objects from the
RollingDice program as follows:
die1 5faceValue
die2 2faceValue
Each object maintains its own faceValue variable, and thus its own state
SEEM 3460 88SEEM 3460 88
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 89SEEM 3460 89
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 90SEEM 3460 90
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 91SEEM 3460 91
RollingDice.java - Sample Execution
The following is a sample execution of RollingDice.class
cuse93> java RollingDiceDie One: 6, Die Two: 1Die One: 4, Die Two: 4Sum: 8Die One: 3, Die Two: 2New sum: 5
SEEM 3460 9292
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;
num1 38
num2 96Before:
num2 = num1;
num1 38
num2 38After:
SEEM 3460 9393
Reference Assignment For object references, assignment copies the address
For example, suppose that name1 and name2 are two object references
title2 = title1;
title1
title2Before:"Steve Jobs"
"Steve Wozniak"
title1
title2After:
"Steve Jobs"
SEEM 3460 9494
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 95SEEM 3460 95
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 96SEEM 3460 96
Packages The classes of the Java standard class library
are organized into packages
Some of the packages in the standard class library are:
Package
java.langjava.appletjava.awtjavax.swingjava.netjava.utiljavax.xml.parsers
Purpose
General supportCreating applets for the webGraphics and graphical user interfacesAdditional graphics capabilitiesNetwork communicationUtilitiesXML document processing
SEEM 3460 97SEEM 3460 97
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 98SEEM 3460 98
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 99SEEM 3460 99
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 100SEEM 3460 100
//*************************************************************// 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 101SEEM 3460 101
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.999999num1 = (int)num2 + 1;System.out.println ("From 1 to 6: " + num1);
}}
SEEM 3460 102SEEM 3460 102
RandomNumbers.java - Sample Execution
cuse93> java RandomNumbersA random integer: -1709988757From 0 to 9: 2From 1 to 10: 9From 20 to 34: 31From -10 to 9: 1A random float (between 0-1): 0.7517807From 1 to 6: 2
The following is a sample execution of RandomNumbers.class
SEEM 3460 103103
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 104104
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
Methods
Data
Client
SEEM 3460 105SEEM 3460 105
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 106SEEM 3460 106
myMethod();
myMethodcompute
Method Control Flow If the called method is in the same class, only
the method name is needed
SEEM 3460 107SEEM 3460 107
doIt helpMe
helpMe();obj.doIt();
main
Method Control Flow The called method is often part of another class
or object
SEEM 3460 108SEEM 3460 108
Method Header A method declaration begins with a method
header
char calc (int num1, int num2, String message)
methodname
returntype
parameter list
The parameter list specifies the typeand name of each parameter
The name of a parameter in the methoddeclaration is called a formal parameter
SEEM 3460 109SEEM 3460 109
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;}
The return expressionmust be consistent withthe return type
sum and resultare local data
They are created each time the method is called, and are destroyed when it finishes executing
SEEM 3460 110110
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 111SEEM 3460 111
Parameters When a method is called, the actual
parameters in the invocation are copied into the formal parameters in the method header
char calc (int num1, int num2, String message){
int sum = num1 + num2;char result = message.charAt (sum);
return result;}
ch = obj.calc (25, count, "Hello");
SEEM 3460 112SEEM 3460 112
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 113SEEM 3460 113
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 114SEEM 3460 114
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.javaSee Account.java
SEEM 3460 115SEEM 3460 115
//*************************************************************// 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 116SEEM 3460 116
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 (acct1);System.out.println (acct2);System.out.println (acct3);
}}
SEEM 3460 117SEEM 3460 117
//*************************************************************// 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 118SEEM 3460 118
//-----------------------------------------------------------------// 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 119SEEM 3460 119
//-----------------------------------------------------------------// 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 120SEEM 3460 120
Transactions.java - Sample Execution
The following is a sample execution of Transactions.class
cuse93> java TransactionsSmith balance after deposit: 540.0Smith balance after withdrawal: 107.75
72354 Ted Murphy $132.9069713 Jane Smith $111.5293757 Edward Demsey $785.90
SEEM 3460 121SEEM 3460 121
Bank Account Exampleacct1 72354acctNumber
102.56balance
name “Ted Murphy”
acct2 69713acctNumber
40.00balance
name “Jane Smith”
SEEM 3460 122122
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