Transcript Object

Java the UML Way
http://www.tisip.no/JavaTheUmlWay/
Using Ready-Made Classes
Objects as models of reality
Client and server, message and operation
Objects and classes
Class diagram
The Car class
One reference assigns to another
The Random class
The String class
Packages
Class constants and class methods
Reading data from the user
version 2002-04-17
page 2-3
page 4
page 5
page 6
page 7-9
page 10
page 11-12
page 13-15
page 16-17
page 18-19
page 20-22
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3
Objects as Models of Reality
• Model – simplification of reality. Focusing on special aspects with
reality.
• Object – a model of a thing that our problem is about.
– focus on knowledge, the object does know a lot of things about itself.
• Examples of objects
– A car has knowledge of its own license plate number, make, and model. It
knows how it starts, how it drives, and how it stops.
– A student knows her own student ID number, her own grades, name, birth
date, and address. She knows how to get to her campus and how she will
answer the questions on the test.
– A meeting knows where it’s being held, who’s participating, when it starts,
and when it’s scheduled to end. Later, it also knows who participated, and
when it actually ended.
• Not just as in reality. These are models, and models are not miniatures
of reality.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 2
Objects in Reality and in Programming
• An object in an object-oriented model is essentially different from the
real object that it models.
• The model object
– has a great deal of knowledge about itself, regardless of whether the real
object is alive, dead, or abstract.
– is responsible for solving a set of problems.
• In continuation, when we talk about objects, we mean the model
objects. If we want to refer to the real objects, we say that in plain text.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 3
Client and Server, Message and Operation
client
server
Greta sends a message to
her car: ”speedUp”
• Client and server are roles that objects
play.
• A client object asks for a service by
sending a message to a server object.
• The message fires an operation by the
server object.
• The server may, or may not, send an
answer back to the client.
Problem 1: State more messages that Greta may send to her car.
Problem 2: Go more thoroughly into the knowledge that a student object
needs to have about itself. State some messages that should be sent to a student object.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 4
Objects and Classes
• An object has
– state: “a condition or situation during the life of an object during which it
satisfies some condition, performs some activity or waits for some event”
- examples?
– attributes: a named quality with a defined range of values - examples?
– identity: all objects can be distinguished from each other.
– behavior: the set of tasks (operations) that the object is able to perform
• Encapsulation is an important characteristic of objects.
– Information about how an object solves tasks is hidden inside the object.
– A client object only relates to the behavior that is defined for the server
object.
• A class is a description of a set of objects that have the same attributes
and same behavior in common.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 5
Class Diagram
• Classes are illustrated using
class diagrams.
• Class diagrams is part of UML
(Unified Modeling Language).
• A class describes a data type.
Car
regNo
make
year
speed
start
speedUp
slowDown
stop
class name
attributes
operations
Solve problem 2 page 55.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 6
The Interface of an Object of the Car Class
•
•
•
The interface of an object is a description of the object's behavior, that is the
messages that a client may send to the object.
These messages are performed as operations.
The operations are programmed as methods. Here is the interface of a car
object:
–
–
–
–
•
•
•
void start( )
void speedUp(int increase)
void slowDown(int decrease)
void stop( )
(formal)
parameters
Two of the methods have parameters. They tell us that we have to send data
together with the messages. In this case the data have to be integers.
The server object may return data to the client after performed the task. If this
is the case, the type of this data is stated before the method name. None of
these here.
The void keyword tells that the server object does not return any message to
the client after it has performed the task.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 7
Using the Car Class
•
•
•
•
In main() we create objects that we send messages to.
main() has functions like a client object, we say that main() is a client
program.
First we have to create an object by using a constructor.
The constructor is in the class, too. The interface of the constructor is (for
example) like this:
–
•
We create an object in this way:
–
•
Car(String regNo, String make, int year, int initSpeed);
Car theCarOfGreta = new Car("VD-12345", "Volvo", 1998, 0);
Now we may send messages to the object (we call the methods):
–
–
(aktuelt)
(actual)
arguments
argument
theCarOfGreta.start();
theCarOfGreta.speedUp(50); class CarTrip {
public static void main(String[] args) {
Car theCarOfTom = new Car("A45456", "Saab", 1995, 0);
theCarOfTom.start();
theCarOfTom.speedUp(50);
theCarOfTom.slowDown(20);
theCarOfTom.stop();
}
A complete client program:
}
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 8
To Create (Instantiate) an Object of a Class
theCarOfGreta
VD-12345
Volvo
1998
0
A reference is a variable containing the address
where the object is stored. For the sake of simplicity,
we are using the name as if it was the name of the
object, and not of a reference to it.
The data type of a reference is simply called a
reference type. String is an example of a reference type.
The other data types we have used until now belongs
to the group of "primitive data types”.
reference name
reserved word to instantiate an object
Car theCarOfGreta = new Car(”VD-12345”, ”Volvo”, 1998, 0);
arguments
class name
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 9
A Reference Is Set to Equal Another Reference
In the beginning:
The car objects have one reference each
theCarOfGreta
theCarOfAnne
Then we execute the statement
theCarOfGreta = theCarOfAnne;
and get the following:
theCarOfGreta
There is no longer any
reference to the other
object; it’ll be removed
from the memory.
theCarOfAnne
Solve problem 1-4, pages 59-60.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 10
The Random Class
randomGen.nextInt(100)
Give me a random number
in the range [0..99]!
76
client
server, the randomGen object
Random randomGen = new Random(seed);
int number1 = randomGen.nextInt(limit);
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 11
A Client Program Using the Random Class
import java.util.Random; // NB!
class TestRandom {
public static void main(String[] args) {
final int limit = 100; // wants numbers in the range [0..99].
final int seed = 17; // the seed should be a prime number
Random randomGen = new Random(seed);
int number1 = randomGen.nextInt(limit);
int number2 = randomGen.nextInt(limit);
int number3 = randomGen.nextInt(limit);
int number4 = randomGen.nextInt(limit);
System.out.println(
"Here you have four random numbers in the range [0.." + (limit - 1) + "]: " +
number1 + " " + number2 + " " + number3 + " " + number4);
}
}
/* Example Run:
Here you have four random numbers in the range [0..99]: 76 20 94 16
*/
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 12
Another Ready-Made Class: the String Class
String city = "Trondheim";
Trondheim
is equivalent to:
String city = new String("Trondheim");
city
VD-12345
Volvo
theCarOfGreta
VD-12345
Volvo
1998
0
theCarOfGreta
here is the
whole truth:
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
1998
0
Chapter 3, page 13
Some of the String Class' approx. 50 Methods
•
•
•
•
•
•
String(String value) // Constructor
char charAt(int position) // Returns the character in the stated position.
// The positions are numbered from 0 on.
int length() // Returns the number of characters in the string.
String toLowerCase() // Creates a new string, equal to the original, but all in lower case.
String toUpperCase() // Creates a new string, equal to the original, but all in upper case.
String trim() // Creates a new string, spaces in the beginning and end are removed
•
Methods searching for a single character or a substring.
– Searching from the beginning:
• public int indexOf(int character)
• public int indexOf(int character, int fromIndex)
• public int indexOf(String subString)
– Searching from the end:
• public int lastIndexOf(int character)
• public int lastIndexOf(int character, int fromIndex)
• public int lastIndexOf(String subString)
• public int lastIndexOf(String subString, int fromIndex)
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 14
An Example Using the String Class
class TestString {
public static void main(String[] args) {
String text = "Anne Smith";
String noTrailingOrLeadingSpaces = text.trim();
String result = "Spaces removed: " + noTrailingOrLeadingSpaces;
String upper = text.toUpperCase();
result = result + "\nOnly upper case letters: " + upper;
String lower = text.toLowerCase();
result = result + "\nOnly lower case letters: " + lower;
char initial = text.charAt(0);
result = result + "\nInitial letter: " + initial;
char secondLetter = text.charAt(1);
result = result + "\nSecond letter: " + secondLetter;
int noOfChars = text.length();
result = result + "\nThe length of the string: " + noOfChars;
System.out.println(result);
}
}
/* Example Run:
Spaces removed: Anne Smith
Only upper case letters: ANNE SMITH
Only lower case letters: anne smith
Initial letter: A
Second letter: n
The length of the string: 10
*/
A
Anne Smith
text
Anne Smith
noTrailingOrLeadingSpaces
ANNE SMITH
upper
anne smith
10
initial
noOfChars
n
secondLetter
lower
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Solve problems 1-3 pp. 69-70.
Chapter 3, page 15
Packages
• A package is a collection of classes. Standard packages:
– graphics, audio and images
– network communication
– database programming
• Every class belongs to a package.
– Most of the classes we create ourselves belong to a nameless package.
– More general classes should be placed in named packages.
• The package name has to be the same as the name of the subdirectory
where the classes are sited.
• The package name is a part of the class name; for example:
java.util.Random.
• This class is in a subdirectory named util under a subdirectory with
name java. The Java compiler and interpreter know where this
subdirectory is placed.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 16
Using Packages
• To use the Random class, we write:
– java.util.Random randomGen = new java.util. Random(seed);
• Instead of writing the whole class name every time, we may insert an
import statement in the beginning of the file:
– import java.util.Random;
• All classes in the package are available by writing:
– import java.util.*;
• NB! You are not allowed to write:
– import java.*.*; // Not allowed!
• Then we may write:
– Random randomGen = new Random(seed);
• It is not necessary to use the import statement for the classes in the
java.lang package.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 17
Class Constants and Class Methods in the Java Library
• The most usual and correct thing is to create objects, and to send
messages to them – the methods are instance methods
• However, a library should provide a few general methods that might be
used without creating objects first, so called class methods
– methods for mathematical calculations (square root, sine, cosine, etc.)
– methods for sorting and searching
• Class methods are marked with the static modifier
– From the java.lang.Math class:
• public static double sqrt(double number)
• public static double sin(double number)
– Example of use:
• double sqRoot = Math.sqrt(15678); // finding the square root of 15678
• The library also contains many constants:
• public static final double PI // this is 3.141592....
– Example of use:
• double circumference = Math.PI * 2 * radius;
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 18
Class Methods for Conversions from Text to Numbers
• An example of use:
String text1 = "2345";
String text2 = "45.3";
int number1 = Integer.parseInt(text1); // interpreting text1 as an integer
double number2 = Double.parseDouble(text2); // interpr. text2 as a decimal numeral
System.out.println(number1 + " " + number2);
• As expected, the output is:
2345 45.3
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 19
Reading Data from the User
The javax.swing.JOptionPane class is used to input data from the user:
String lengthInput =
JOptionPane.showInputDialog(
"The length of the wall (meters): ");
String heightInput =
JOptionPane.showInputDialog(
"The height of the wall (meters): ");
JOptionPane.showMessageDialog(null,
"The area of the wall is " + area + " square meters.");
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 20
Here is the Complete Program
/*
* WallCalculations2.java E.L. 2001-06-16
*/
import javax.swing.JOptionPane;
class WallCalculations2 {
public static void main(String[] args) {
String lengthInput = JOptionPane.showInputDialog("The length of the wall (meters): ");
String heightInput = JOptionPane.showInputDialog("The height of the wall (meters): ");
double length = Double.parseDouble(lengthInput);
double height = Double.parseDouble(heightInput);
double area = length * height;
JOptionPane.showMessageDialog(null,
"The area of the wall is " + area + " square meters.");
System.exit(0);
}
}
/* Example Run:
Length: 5.8 m
Height: 2.4 m
The area of the wall is 13.92 square meters.
*/
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 21
More Examples
JOptionPane.showMessageDialog(null,
"The simplest message dialog");
JOptionPane.showMessageDialog(null,
"To the left you see the error message icon",
"The method with four parameters",
JOptionPane.ERROR_MESSAGE);
ImageIcon image = new ImageIcon("blue.gif");
JOptionPane.showMessageDialog(null,
"A gif file with a blue square",
"The method with five parameters", 0, image);
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 3, page 22