Upload
profesorjavacom
View
1.234
Download
5
Embed Size (px)
DESCRIPTION
Citation preview
Esta obra está bajo una licencia Reconocimiento 2.5 México de Creative Commons. Para ver una copia de esta licencia, visite http://creativecommons.org/licenses/by/2.5/mx/ o envíe una carta a Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
Acerca de: En la compilación de esta obra se utilizaron libros conocidos en el ambiente Java, gráficas, esquemas, figuras de sitios de internet, conocimiento adquirido en los cursos oficiales de la tecnología Java. En ningún momento se intenta violar los derechos de autor tomando en cuenta que el conocimiento es universal y por lo tanto se puede desarrollar una idea a partir de otra. La intención de publicar este material en la red es compartir el esfuerzo realizado y que otras personas puedan usar y tomar como base el material aquí presentado para crear y desarrollar un material mucho más completo que pueda servir para divulgar el conocimiento.
Atte. ISC Raúl Oramas Bustillos.
• Anatomy of a Simple Java Program
• Built-In Data Types
• Autoincrement/Decrement Operators
• Java Expressions
• Casting
• Block Structured Languages and the Scope of a Variable
• Controlling a Program’s Execution Flow.
• Exercises
Java Language Basics
Java Expressions.
An expression is a combination of one or more operators and operands.
Expressions usually perform a calculation. The value calculated does not have to
be a number, but it often is. The operands used in the operations might be
literals, constants, variables, or other sources of data.
Many programming statements involve expressions. Expressions
are combinations of one or more operands and the operators used
to perform a calculation.
Casting
• Java automatically casts implicitly to larger data types.
• When placing larger data types into smaller types, you must use explicit
casting to state the type name to which you are converting.
Casting
The rules governing automatic casting by the Java compiler are as follows when
considering two operands within an arithmetic expression:
– If either type is double, the other is cast to a double
– If either type is float, the other is cast to a float
– If either type is long, the other is cast to a long
– Else both operands are converted to int
Casting
int num1 = 53;
int num2 = 47;
byte num3 = (byte)(num1 + num2) //ok nhpp
int valor;
long valor2 = 99L;
valor = (int)valor2; //no hay pérdida de precisión
int valor;
long valor2 = 123987654321;
valor = (int)valor2; //el número se trunca
Casting
short s = 259; //binario 100000011
byte b = (byte)s; //casting
System.out.println(“b = ” + b);
0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1
b = (byte)s
0 0 0 0 0 0 1 1
Block Structured Languages and the Scope of a Variable
Java is a block structured language. A “block” of code is a series of zero or more
lines of code enclosed within curly braces {…}
Conditional Statement Types: if-else
• An if-else statement is a conditional expression that must return a
boolean value
• else clause is optional
• Braces are not needed for single statements but highly recommended for
clarity
Controlling a Program’s Execution Flow. If-else: ?
• Shortcut for if-else statement:
(<boolean-expr> ? <true-choice> : <false-choice>)
• Can result in shorter code
–Make sure code is still readable
Controlling a Program’s Execution Flow. Switch
• Switch statements test a single variable for several alternative values
• Cases without break will “fall through” (next case will execute)
• default clause handles values not explicitly handled by a case
Looping Statement Types: while
• Executes a statement or block as long as the condition remains true
• while () executes zero or more times’
• do...while() executes at least once.
Looping Statement Types: for
• A for loop executes the statement or block { } which follows it
– Evaluates "start expression" once
– Continues as long as the "test expression" is true
– Evaluates "increment expression" after each iteration
• A variable can be declared in the for statement
– Typically used to declare a "counter" variable
– Typically declared in the “start” expression
– Its scope is restricted to the loop
for vs. while
• These statements provide equivalent functionality
– Each can be implemented in terms of the other
• Used in different situations
– while tends to be used for open-ended looping
– for tends to be used for looping over a fixed number of iterations
Branching statements
• break
– Can be used outside of a switch statement
– Terminates a for, while or do-while loop
– Two forms:
• Labeled: execution continues at next statement outside the loop
• Unlabeled: execution continues at next statement after labeled loop
Branching statements
• continue
– Like break, but merely finishes this round of the loop
– Labeled and unlabeled form
• return
– Exits the current method
– May include an expression to be returned
• Type must match method’s return type
• Return type “void” means no value can be returned
57
• Simplification Through Abstraction
• Generalization Through Abstraction
• Reuse of Abstractions
• Inherent Challenges
• Exercises
Abstraction and Modeling
58
Abstraction: a process that involves recognizing and focusing
on the important characteristics of a situation or object, and
filtering out or ignoring all of the unessential details.
– Is the process of ignoring details to concentrate on essential
characteristics
– Is the primary means of coping with complexity
– Simplifies user’s interaction with abstracted objects
Simplification Through Abstraction
61
As an abstraction, a road map represents those features of a given geographic
area relevant to someone trying to navigate with the map, perhaps by a car:
major roads and places of interest, obstacles such as major bodies of water, etc.
Of necessity, a road map cannot include every building, tree, street sign,
billboard, traffic light, fast food restaurant, etc. that physically exists in the real
world. If i did, then it would be so cluttered as to be virtually unusable; none of
the important features would stand out.
Simplification Through Abstraction
62
Compare a road map with a topographical map, a climatological
map, and a population density map of the same region: each
abstracts out different features of the real world – namely, those
relevant to the intender user of the map in question.
Simplification Through Abstraction
63
As another example, consider a landscape. An artist may look at the landscape
from the perspective of colors, textures, and shapes as a prospective subject for
a painting.
Simplification Through Abstraction
64
A homebuilder may look at the same landscape from the perspective of where
the best building site may be on the property, assessing how many trees will need
to be cleared to make way for a construction project.
Simplification Through Abstraction
66
If we eliminate enough detail from an abstraction, it becomes
generic enough to apply to a wide range of specific situations
or instances. Such generic
abstractions can often be
quite useful. For example,
a diagram of a generic cell
in the human body might
include only a few features
of the structures that
are found in an actual cell:
Generalization Through Abstraction
67
This overly simplified diagram doesn’t look like a real nerve cell, or a real
muscle cell, or a real blood cell; and yet, it can still be used in a educational
setting to describe certain aspects of the structure and function of all of these
cell types – namely, those features that the various cell types have in common.
Generalization Through Abstraction
68
Even though our brains are adept at abstracting concepts such as road maps and
landscapes, that still leaves us with hundreds of thousands, if not millions, of
separate abstractions to deal with over our lifetimes. To cope with this aspect of
complexity, human beings systematically arrange information into categories to
established criteria; this process is known as classification.
Organizing Abstractions Into Classification Hierarchies
71
For example, science categorizes all natural objects as belonging to either the
animal, plant, or mineral kingdom. In order for a natural object to be classified
as an animal, it must satisfy the following rules:
It must be a living being
It must be capable of spontaneous movement
It must be capable of rapid motor response to stimulation
Organizing Abstractions Into Classification Hierarchies
72
The rules for what constitute a plant, on the other hand, are diferent:
It must be a living being (same as for an animal)
It must lack an obvious nervous system
It must possess cellulose cell walls
Organizing Abstractions Into Classification Hierarchies
73
Given clear-cut rules such as these, placing an object into the appropriate
category, or class, is rather straightforward. We can then “drill down”,
specifying additional rules which differentiate various types of animal, for
example, until we’ve built up a hierarchy of increasing more complex
abstractions from top to bottom.
Organizing Abstractions Into Classification Hierarchies
74
A simple example of an abstraction hierarchy is shown below.
Organizing Abstractions Into Classification Hierarchies
Natural Objects
Plant Animal Mineral
Mammal Fish Bird Reptile Insect
Dog Cat Monkey
75
When thinking about an abstraction hierarchy such as the one shown previously,
we mentally step up and down thehierarchy, automatically zeroing in on only the
single layer or subset of the hierarchy (known as a subtree) that is important
to us at a given point in time. For example, we may only be concerned with
mammals, and so can focus on the mammalian subtree:
Organizing Abstractions Into Classification Hierarchies
Mammal
Dog Cat Monkey
76
We temporarily ignore the rest of the hierarchy. By doing so, we automatically
reduce the number of concepts that we mentally need to “juggle” at any one
time to a manageable subset of the overall abstraction hierarchy; in the
simplistic example, we are now dealing with only four concepts rather than the
original 13. No matter how complex an abstraction hierarchy grows to be, it
needn’t overwhelm us if it is properly organized.
Organizing Abstractions Into Classification Hierarchies
Mammal
Dog Cat Monkey
77
Coming up with precisely which rules are necessary to properly classify an object
within an abstraction hierarchy is not always easy. Take for example, the rules
we might define for what constitutes a bird: namely, something which:
Has feathers
Has wings
Lays eggs
Is capable of flying
Organizing Abstractions Into Classification Hierarchies
78
Given these rules, neither an ostrich nor a penguin could be classified as a bird,
because neither can fly.
Organizing Abstractions Into Classification Hierarchies
Birds Non-Birds
79
If we attempt to make the rule set less restrictive by eliminating the “flight”
rule, we are left with:
Has feathers
Has wings
Lays eggs
According to this rule set, we now may properly classify both the ostrich and the
penguin as birds.
Organizing Abstractions Into Classification Hierarchies
81
This rule set is still unnecessarily complicated, because as it turns out, the “lays
eggs” rule is redundant: whether we keep it or eliminate it, it doesn’t change our
decision of what constitutes a bird versus a non-bird. Therefore, we simplify
the rule set once again:
Has feathers
Has wings
Organizing Abstractions Into Classification Hierarchies
82
We try to take our simplification process one step further, by eliminating yet
another rule, defining a bird as something which:
Has wings
We’ve gone too far this time: the abstraction of a bird is now so general that
we’d include airplanes, insects, and all sorts of other non-birds in the mix.
Organizing Abstractions Into Classification Hierarchies
83
Organizing Abstractions Into Classification Hierarchies
The process of rule definition for purposes of categorization
involves “dialing in” just the right set of rules –not too general,
not to restrictive, and containing no redundancies- to define
the correct membership in a particular class.
84
When pinning down the requirements for an information systems development
project, we typically start by gathering details about the real world definition on
which the system is to be based. These details are usually a combination of:
Those that are explicitly offered to us as we interview the intended users of
the system
Those that we otherwise observe.
Abstractions as the Basis for Software Development
85
We must make a judgment all as to which of these details are relevant to the
system’s ultimate purpose. This is essential, as we cannot automate them all!.
To include too much details is to overly complicate the resultant system, making
it that much more difficult to design, program, test, debug, document, maintain,
and extend in the future.
As with all abstractions, all of our decisions of inclusions versus elimination when
building a software system must be made within the context of the overall
purpose and domain, or subject matter focus, of the future system.
Abstractions as the Basis for Software Development
86
Once we’ve determined the essential aspects of a situation we can prepare a
model of that situation. Modeling is the process by which we develop a pattern
for something to be made. A blueprint for a custom home, a schematic diagram
of a printed circuit, and a cookie cutter are all examples of such patterns.
Abstractions as the Basis for Software Development
88
• Modeling achieves four aims:
– Helps you to visualize a system as you want it to be.
– Permits you to specify the structure or behavior of a system.
– Gives you a template that guides you in constructing a system.
– Documents the decisions you have made.
• You build models of complex systems because you cannot comprehend such a
system in its entirety.
• You build models to better understand the system you are developing.
Abstractions as the Basis for Software Development
89
The importance of modeling:
Abstractions as the Basis for Software Development
Paper Airplane Fighter Jet
Less Important More Important
90
• Many software teams build applications approaching the problem like they
were building paper airplanes
– Start coding from project requirements
– Work longer hours and create more code
– Lacks any planned architecture
– Doomed to failure
• Modeling is a common thread to successful projects
Abstractions as the Basis for Software Development
91
An object model of a software system is such a pattern. Modeling and
abstraction go hand in hand, because a model is essentially a physical or
graphical portrayal of an abstraction; before we can model something effectively,
we must have determined the essential details of the subject to be modeled.
Abstractions as the Basis for Software Development
92
When learning about something new, we automatically search our “mental
archive” for other abstractions/models that we’ve previously built and mastered,
to look for similarities that we can build upon.
When learning to ride a two-wheeled
bicycle for the first time, for example,
you may have drawn upon lessons
that you learned about riding a
tricycle as a child.
Reuse of Abstractions
93
Both have handlebars that are used to steer; both have pedals that are used to
propel the bike forward. Although the Abstractions didn’t match perfectly –a
two– wheeled bicycle introduced the new challenge of having to balance oneself –
there was enough of a similarity to allow you to draw upon the steering and
pedaling expertise you already had mastered, and to focus on learning the new
skill of how to balance on two wheels.
Reuse of Abstractions
94
Reuse of Abstractions
This technique of comparing features to find an abstraction
that is similar enough to be reused successfully is known as
pattern matching and reuse. A pattern reuse is an
important technique for object oriented software development
,as well, because it spares us from having to reinvent the
wheel with each new project. If we can reuse an abstraction
or model from a previous project, we can focus on those
aspects of the new project that differ from the old, gaining
a tremendous amount of productivity in the process.
98
Despite the fact that abstraction is such a natural process for human beings,
developing an appropriate model for a software system is perhaps the most
difficult aspect of software engineering.
Inherent Challenges
101
• What is an object?
• Methods
• Reuse of Abstractions
• Inherent Challenges
• Exercises
Objects and Classes
102
A class is a collection of objects with related properties and behaviours.
In real-life we group things into classes to help us reduce complexity
Example:
The set of all dogs forms the class Dog
Each individual dog is an object of the class Dog
Firulais, Terry and Rex are all instances of the class Dog
To some extent, we can interact with Firulais based on our knowledge of dogs
in general, rather than Firulais himself
What Is an Object?
104
What is a Waiter?
A Waiter is someone who has the following properties and behaviours:
Properties of a Waiter
Full Name
Behaviours of a Waiter
Bring menus
Take orders
Bring meals
This collection of properties and behaviours defines the class of Waiters
Because these behaviours are standardized, we can deal with any Waiter just
based on our “general knowledge” of Waiters
What Is an Object?
105
A class is a general description of the properties and behaviours of some
entities.
We described the class Waiter
giving the general description
of what properties Waiters have
and what things Waiters can
do.
What Is an Object?
Waiter
fullName
bringMenu
takeOrder
bringMeal
Name of
class
Properties
Behaviours
106
An object is a specific member of a class.
An object belonging to the class of Waiters is an actual individual waiter
Pierre is an object of the class Waiter, and so is Bill and so is Jimmy –they
can all take orders, bring menus and bring meals
What Is an Object?
109
What Is an Object?
Classes in Java may have methods and attributes.
– Methods define actions that a class can perform.
– Attributes describe the class.
111
What Is an Object?
The phrase "to create an
instance of an object“ means
to create a copy of this object
in the computer's memory
according to the definition of
its class.
115
The class BankAccount
A bank account has the following properties:
An account number and account name
A balance
A bank account has the following behaviours:
Money can be credited to the bank account
Money can be debited from the bank account
What Is an Object?
118
The arguments in the constructor are used to specify initial information about
the object. In this case they represent the account number and account name.
A constructor can have any number of arguments including zero.
What Is an Object?
Arguments
120
What Is an Object?
1. Declare a reference.
2. Create the object.
Two references to two
objects, with values
for their attributes.
122
What Is an Object?
Heap memory Stack memory
428802
0x99f311
0x334009 AnotherShirt
myShirt
id
‘\u0000’
0.0
false
‘\u0000’
0.0
false
size
size
price
price
lSleeved
lSleeved
123
What Is an Object?
Heap memory Stack memory
0x99f311
0x334009
0x99f311
AnotherShirt
myShirt
‘\u0000’
0.0
false
‘\u0000’
0.0
false
size
size
price
price
lSleeved
lSleeved
X X
124
Consider a class that represents a circle.
public class Circle {
int radius;
}
public class ShapeTester {
public static void main(String args[]) {
Circle x;
x = new Circle();
System.out.println(x);
}
}
What Is an Object. Examples.
125
Here is another example defining a Rectangle that stores a width and height as
doubles:
public class Rectangle {
double width = 10.128;
double height = 5.734;
}
public class ShapeTester {
public static void main(String args[]) {
Circle x;
Rectangle y;
x = new Circle();
y = new Rectangle();
System.out.println(x + " " + y);
}
}
What Is an Object. Examples.
126
public class ShapeTester {
public static void main(String args[]) {
Circle x;
Rectangle y, z;
x = new Circle();
y = new Rectangle();
z = new Rectangle();
System.out.println(x + " " + y + " " + z);
}
}
What Is an Object. Examples.
127
public class ShapeTester {
public static void main(String args[]) {
Circle x;
Rectangle y, z;
x = new Circle();
y = new Rectangle();
z = new Rectangle();
x.radius = 50;
z.width = 68.94;
z.height = 47.54;
System.out.println(x.radius + " " + y.width + " " + z.width);
}
}
What Is an Object. Examples.
130
The interesting part of OO-Programming is getting the objects to interact
together. This is obvious when we look at real world examples:
– A house not being lived in is not useful
– A BankAccount in which no money is deposited or withdrawn is not useful
either
– A CD without a CD Player is useless too.
Behaviour represents:
– the things you can do with an object (i.e., a command)
– information you can ask for from an object (i.e., a question)
Methods
131
By definition an instance is created from its class definition and so it only uses
the vocabulary defined in its own class. To help us understand object behaviour,
we should try to think of objects as being “living” entities. When we want to
"talk to" or "manipulate" an object, we must send it a message.
A message:
– is a set of one or more words (joined together as one) that is sent to an
object.
– is part of the "vocabulary" that an object understands.
may have additional information (parameters) which are required by the object.
You can send messages to objects, and they respond to you:
Methods
132
May have additional information (parameters) which are required by the object.
You can send messages to objects, and they respond to you:
Objects only respond if they understand what you say:
Methods
134
Thus, by defining behaviour, we simply add to the vocabulary of words (i.e.,
messages) that the object understands. Objects communicate by sending
messages back and forth to each other:
Methods
135
As we can see, many objects are often involved in a more difficult task. For
example, consider building a house. A person asks a house building company to
build them a house. In fact, the house building company then "sub-contracts"
out all of the work in that it then hires others to do all the work. So the house
builder actually co-ordinates the interactions with all of the contractors. The
contractors themselves contact suppliers to get their parts as well as other
helpers to help them accomplish their tasks:
Methods
137
To define a particular behaviour for an object, we must write a method
A method :
– is the code (expressions) that defines what happens when a message is
sent to an object.
– may require zero or more parameters (i.e., pieces of data):
• Parameters may be primitives or other objects
• Primitives are “passed-by-value” (the actual value is “copied” and
passed with the message)
• Objects are “passed-by-reference” (a pointer to the object is passed
with the message)
– may be either a class method or an instance method.
Methods are typically used to do one or more of these things:
get information from the object it is sent to change the object in some way
compute or do something with the object
obtain some result.
Methods
138
Methods are typically used to do one or more of these things:
– get information from the object it is sent to
– change the object in some way
– compute or do something with the object
– obtain some result.
Methods
140
Sending a message to an object is also known as calling a method. So the
method is actually the code that executes when you send a message to an
object. Some methods return answers, others may do something useful but do
not return any answer.
Methods
141
A method is calling by specifying
The target object, following by a dot
The method name
The method arguments (is there are any)
cheque.getBalance();
The target object is the one called cheque
The getBalance method has been called
There are no arguments for this method
The result will be returned to whoever called the method
Methods
147
In general, methods calls may
Send information to the target, or not
Receive information from the object, or not
The method signature tell us whether information is to be sent,
received or both.
Methods
152
Data Structures.
A data structure can be thought of as container that is used to
group multiple elements into a single representation, and is
used to store, retrieve, and manipulate the contained data.
153
Basic Data Structure Mechanisms.
Before the development of the Java2 platform, only a small set
of classes and interfaces were available in the supplied
Standard Class. Library for data store manipulation.
– Arrays
– Vector
– Stack
– Hashtable
– Properties
– BitSet
– Enumeration
154
The Vector Class.
• Contains a collection of object references.
• Can vary in size.
• Can hold objects of different types.
• The Vector class is more flexible than an Array:
166
Enumeration Interface.
The Enumeration interface allows the developer to traverse
collections at a high level, with little concern for the underlying
collection.
Used specifically when traversal order is not important.
Vector's elements() method and Hashtable's keys() and
elements() methods return Enumeration objects.
The Enumeration interface contains two methods:
hasMoreElements() and nextElement()
170
Set Interface.
• The Set interface adds no methods to the collection interface.
• Set collections add the restriction of no duplicates.
• boolean add(Object element) fails to update the collection and returns false if
the element already exists.
• Adds a stronger contract on the behavior of the equals and hashCode
operations, allowing Set objects with different implementation types to be
compared.
173
Iterator Interface.
The Iterator interface is used to traverse through each element
of a collection. This interface offers the same functionality as
the Enumeration interface, with an additional method that
enables us to remove an object. The presence of this
additional method makes it preferable over the Enumeration
interface.
• Object next()
• boolean hasNext()
• void remove()
175
List Interface.
A List is a collection of elements in a particular order. Also
referred to as a sequence, a List can contain duplicate
elements.
The List interface extends from the Collection interface an has
an index of elements. The index, which is an integer, denotes
the position of elements in the list. The index also helps us
include a new element into a list in the specific position
required.
183
Overview of Object Orientation.
• Technique for system modeling
• Models the system as a number of related objects that interact
• Similar to the way people view their environment
Object technology is a set of principles guiding software
construction together with languages, databases, and
other tools that support those principles. (Object
Technology: A Manager’s Guide, Taylor, 1997)
185
Identifying Objects.
• Object can be a sentence, bank account, number, or
car
• Objects are:
– Things
– Real or imaginary
– Simple or complex
An object is an entity with a well-defined boundary and
identity that encapsulates state and behavior.
186
Identifying Objects.
An object is an entity with a well-defined boundary and
identity that encapsulates state and behavior.
188
Identifying Objects.
Physical entity
Conceptual entity
(Chemical process)
Software entity
(Linked list)
189
Identifying Objects.
• Objects have many forms:
– Tangible things (Airplane, Computer, Car)
– Roles (Doctor, Teacher)
– Incidents (Meeting)
– Interactions (Interview, Agreement)
190
Object definition. Case Study
• Throughout this course, a case study of a clothing catalog, DirectClothing,
Inc., will be used to illustrate concepts.
191
Object definition. Case Study
• Most projects start by defining the problem domain by gathering customer
requirements and by writing a statement of scope that briefly states what
you, the developer, want to achieve.
• For example, a scope statement for the DirectClothing project might be:
“Create a system allowing order entry people to enter and accept
payment for an order.”
• After you have determined the scope of the project, you can begin to identify
the objects that will interact to solve the problem.
192
Object definition. Case Study
• Object names are often nouns, such as “account” or “shirt.” Object
attributes are often nouns too, such as “color” or “size.” Object operations
are usually verbs or noun-verb combinations, such as“display” or “submit
order.”
• Your ability to recognize objects in the world around you will help you to
better define objects when approaching a problem using object-oriented
analysis.
Solution
193
Object definition. Case Study
• The problem domain of the DirectClothing, Inc. case study has the following
nouns. Each could be an object in the catalog’s order entry system.
catalog
clothing
subscribers
closeout items
monthly items
normal items
order
194
Object definition. Case Study
customer
CSR ( customer service representative)
order entry clerk
Supplier
Payment
warehouse
credit car
order entry
mail order
fax order
online order
195
Object definition. Case Study
inventory
back-ordered items
system
Internet
business
year
month
order form
check
196
Identifying Object Attributes and Operations
• Example:
– Cloud attributes: size, water content, shape
– Cloud operations: rain, thunder, snow
Attributes: an object’s characteristics
Operations: what an object can do
198
Identifying Object Attributes and Operations. Case Study
• When you are attempting to assign operations to an object, operations
performed on an object are assigned to the object itself. For example, in a
bank an account can be opened and closed, balanced and updated, receive
additional signers, and generate a statement. All of these would be the
Account object’s operations.
199
Identifying Object Attributes and Operations. Case Study
• For the Order object, the following attributes and operations could be
defined:
– Attributes: orderNumber, customerNumber, dateOrdered,
amountOwed
– Operations: whatCustomer, calcAmountOwed, printOrder,
payOrder
• What would be the attributes and operations for the Customer object?
200
Testing an Identified Object:
• Use the following criteria to test object validity:
– Relevance to the problem domain
– Need to exist independently
– Having attributes and operations
201
Relevance to the Problem Domain.
• Does it exist within the boundaries of the problem statement?
• Is it required in order for the system to fulfill its responsibility?
• Is it required as part of interaction between a user and the system?
• Can objects sometimes be a characteristic of other objects?
202
Testing an Identified Object. Case Study
• The Order object exists within the boundaries of the problem statement, it is
required for the system to fulfill its responsibilities, and as part of an
interaction between a user and the system. The Order object passes the test.
• Test the other candidate objects in the case study. What are the results?
203
Testing an Identified Object. Case Study
The following objects can probably be removed from the list:
• Internet, system, business – Not necessary within the boundaries of the
problem statement
• month, year – May be attributes of the date of an order being placed, but not
necessary as an object itself
204
Testing an Identified Object. Case Study
The following objects can probably be removed from the list:
• online order, fax order, mail order – Can probably be captured as special cases
of the order object, or you could have a type attribute on the order object to
indicate how the order was made. You may not want to eliminate here, but to
note these nouns are special cases.
• back-ordered items, closeout items, monthly sales item – Can probably be
captured as special cases of a normal item object. You may not want to
eliminate these nouns, but to note these are special cases.
205
Independent Existence.
• To be an object and not a characteristic of another object, the object must
need to exist independently
206
Independent Existence. Case Study
• Can an Order object exist without any of the other objects? It can, but in use,
it must have an associated Customer object.
• Address could be an attribute of Customer, but in this case study it is
advantageous for Address to be a separate object.
207
Attributes and Operations.
• An object must have attributes and operations
• If it does not, it is probably and attribute or operation of another object
208
Attributes and Operations. Case Study
• An object must have attributes and operations. If you cannot define attributes
and operations for an object, then it probably is not an object but an
attribute or operation of another object.
• The Order object has many attributes and operations defined, as do most of
the candidate objects.
209
Encapsulation.
• Encapsulation separates the external aspects of an object from the internal
implementation details
• Internal changes need not affect external interface
Hide
implementation
from clients.
Clients depend
on interface
211
Implementing Encapsulation.
• An object’s attributes and operations are its members
• The members of an object can be public or private
• In pure OO systems, all attributes are private and can be changed or accessed
only through public operations
213
Overview of Object Orientation.
• Technique for system modeling
• Models the system as a number of related objects that interact
• Similar to the way people view their environment
Object technology is a set of principles guiding software
construction together with languages, databases, and
other tools that support those principles. (Object
Technology: A Manager’s Guide, Taylor, 1997)
214
Class Overview.
• A class is a description of a set of objects that share the same attributes,
operations, relationships, and semantics.
– An object is an instance of a class.
• A class is an abstraction in that it Emphasizes relevant characteristics.
Suppresses other characteristics.
217
Class Overview.
• A class is an abstract definition of an object. It defines the structure and
behavior of each object in the class. It serves as a template for creating
objects.
• Classes are not collections of objects.
218
Class Overview.
• An attribute is a named property of a class that describes a range of values
that instances of the property may hold.
• A class may have any number of attributes or no attributes at all.
219
Class Overview.
• An operation is the implementation of a service that can be requested from
any object of the class to affect behavior.
• A class may have any number of operations or none at all.
220
Generalization
Generalization identifies and defines the common attributes
and operations in a collection of objects.
Example: Transport is a generalization of several classes that
provide transportation.
221
Generalization
A relationship among classes where one class shares the
structure and/or behavior of one or more classes.
222
Inheritance
• Is a mechanism for defining a new class in terms of an existing class.
• Allows you to group related classes so that they can be managed collectively.
• Promotes reuse.
• Allows you to hide or override inherited members.
• Relevant terms: generalization, specialization, override.
227
Specialization
Specialization is inheritance with the addition and modification
of methods to solve a specific problem.
228
Polymorphism
• Allows you to implement an inherited operation in a subclass
• Works only when the common operation gives the same semantic result
• Implementation of a polymorphic function depends on the object it is applied
to
• Can be used only with inheritance
229
Polymorphism
Polymorphism is the ability to hide many different
implementations behind a single interface.
232
Object Messaging.
• One object sends a message to another (the receiving object)
• The receiving object may send other messages, change its attribute, or read
in any other appropriate way.
• Messaging in handled by operations in the public interface of the receiving
object.
233
Association and Composition.
• Objects interact through one of two relationships: association or
composition.
• Association: Two independent objects collaborate to achieve some goal, like a
person using a computer (“uses a ” relationship)
• Composition: One object contains another, like a pencil that has a lead (“has
a” relationship)
248
Object-Oriented Analysis and Design.
• Unified Modeling Language (UML) is used to notate the design.
• UML diagrams:
– Use case diagram
– Sequence diagram
– Class diagrams
– Activity diagrams
249
Use Case Diagrams.
• A use case diagram contains use cases, actors, and relationship links
• A use case is an interaction of a user with the application in order to achieve a
desired result
• An actor is a role that a user plays when interfacing with the application
• Relationship links between use cases are “uses” and “extends.”
250
Use Case Diagrams.
• There are two types of relationship links that can be made in the diagram.
These are the extends and uses relationships between the use cases.
• The extends relationship links two use cases that are similar but one does a
little more than the other. It is implied that the actor who performs the first
use case will also perform the extension use case. This relationship is
indicated by <<extends>> on the link’s line.
251
Use Case Diagrams.
• The second type of link is the uses relationship, which occurs when there is a
behavior that is used by many use cases. To avoid repetition, make that
behavior a use case itself, and have other use cases “use” it. It is implied that
an actor does not perform the “used” use case, but that the base use case
does the performing.
• This relationship is indicated by <<uses>> on the link’s line.
252
Use Case Diagrams.
• An actor represents anything that interacts with the system.
• A use case is a sequence of actions a system performs that yields an
observable result of value to a particular actor.
255
Use Case Diagrams.
Follow these steps to create a use case diagram:
1. Identify each use case in your application. (It might help to identify events
you need to react to.)
2. Draw and label each of the actors of the application.
3. Draw and label the use cases of the application.
4. Draw the links from the actor to the use cases they perform.
5. Write a short description of each use case. The diagram and the description
together will give a representation of the functionality that must be
implemented in the system.
256
Example: Use Case Diagrams.
A use case specifies a set of scenarios
for accomplishing something
useful for an actor. In this
example, one use case is
"Buy soda."
258
Example: Use Case Diagrams.
Collecting the money
from a soda machine
is another
important use case.
260
Use Case Diagrams.
Use case diagrams describe what a system does from the
standpoint of an external observer. The emphasis is on what
a system does rather than how.
Use case diagrams are closely connected to scenarios. A
scenario is an example of what happens when someone
interacts with the system.
261
Use Case Diagrams.
Here is a scenario for a medical clinic:
"A patient calls the clinic to make an appointment for a
yearly checkup. The receptionist finds the nearest empty time
slot in the appointment book and schedules the appointment
for that time slot. "
262
Use Case Diagrams.
A use case is a summary of scenarios for a single task or
goal. An actor is who or what initiates the events involved in
that task. Actors are simply roles that people or objects play.
The picture below is a Make Appointment use case for the
medical clinic. The actor is a Patient. The connection between
actor and use case is a communication association (or
communication for short).
263
Use Case Diagrams.
A use case diagram is a collection of actors, use cases, and
their communications. We've put Make Appointment as part of
a diagram with four actors and four use cases. Notice that a
single use case can have multiple actors.
264
Use Case Diagrams.
A use case describes a single task or goal and is indicated by
an oval. The task or goal is written inside the oval and usually
it contains a verb.
265
Use Case Diagrams.
TIP: Start by listing a sequence of steps a user might take in
order to complete an action. For example a user placing an
order with a sales company might follow these steps.
1. Browse catalog and select items.
2. Call sales representative.
3. Supply shipping information.
4. Supply payment information.
5. Receive conformation number from salesperson.
267
Exercises: Use Case Diagrams.
Diseñar diagramas de casos de uso para las siguientes
situaciones:
• Comprar una paleta en la cafetería de la escuela.
• Cancelar una cita con el(la) novio(a) ó una salida con los amigos.
• Enviar un mensaje de correo electrónico.
• Enviar un mensaje de texto de un teléfono celular a otro.
• Copiar un archivo a la memoria USB.
• Imprimir un documento de Word en el centro de cómputo.
268
Use Case Relations.
<<extend>> (extensión) : Los casos de uso pueden
extenderse a otros casos de uso. Se recomienda utilizar
cuando un caso de uso es similar a otro (características).
269
Use Case Relations.
<<include>> (inclusión) : Los casos de uso pueden incluir a
otros casos de uso. Se recomienda utilizar cuando se tiene
un conjunto de características que son similares en más de
un caso de uso y no se desea mantener copiada la
descripción de la característica.
270
Use Case Relations.
<<include>>
Cuando un número de casos de uso comparten un
comportamiento común puede ser descrito por un caso de
uso que es utilizado por otros casos de uso.
271
Use Case Relations.
<<extends>>
Es una relación de dependencia donde un caso de uso
extiende otro caso de uso añadiendo acciones a un caso de
uso extendido.
272
Example: Use Case Diagrams.
Máquina Recicladora: Sistema que controla una máquina
de reciclamiento de botellas, tarros y jabas. El sistema debe
controlar y/o aceptar:
• Registrar el número de ítems ingresados.
• Imprimir un recibo cuando el usuario lo solicita:
• Describe lo depositado
• El valor de cada item
• Total
273
Example: Use Case Diagrams.
• Existe un operador que desea saber lo siguiente:
– Cuantos ítems han sido retornados en el día.
– Al final de cada día el operador solicita un resumen de todo lo
depositado en el día.
• El operador debe además poder cambiar:
– Información asociada a ítems.
– Dar una alarma en el caso de que:
• Item se atora.
• No hay más papel.
275
Example: Use Case Diagrams.
Un Cliente puede depositar Items y un Operador puede
cambiar la información de un Item o bien puede Imprimir un
Informe.
277
Example: Use Case Diagrams.
la impresión de comprobantes, que puede ser realizada
después de depositar algún item por un cliente o bien puede
ser realizada a petición de un operador.
279
Example: Use Case Diagrams.
Sistema de ventas. Un sistema de ventas debe interactuar
con clientes, los cuales efectúan pedidos. Además los clientes
pueden hacer un seguimiento de sus propios pedidos. El
sistema envía los pedidos y las facturas a los clientes. En
algunos casos, según la urgencia de los clientes, se puede
adelantar parte del pedido (pedidos parciales).
281
Exercises: Use Case Diagrams.
Encontrar los casos de uso para la biblioteca sencilla:
• De cada libro tengo uno o varios ejemplares.
• Cada usuario puede mantener un máximo de tres ejemplares en préstamo
de forma simultánea.
• Los usuarios pueden solicitar al bibliotecario un libro en préstamo (dando
el autor o el título, etc.) y el sistema debe determinar si hay al menos un
ejemplar en las estanterías. Si es así, el bibliotecario entrega un ejemplar
y registra el préstamo (usuario, fecha y ejemplar concreto).
282
Exercises: Use Case Diagrams.
• El préstamo es semanal y si se produce un retraso en la devolución, se
impone una multa en forma de días sin derecho a nuevos préstamos (3 días
por cada día de retraso).
• Antes de cualquier préstamo, el bibliotecario debe comprobar esta
situación.
285
Sequence Diagrams.
• Capture the operations of a single use case and show how groups of objects
collaborate on those operations.
• Exist for each use case.
• Contains objects, objects lifelines, messages between objects, conditions,
iteration markers, activations, and object deletions.
286
Sequence Diagrams.
• A Sequence Diagram is an interaction diagram that emphasizes the time
ordering of messages.
• The diagram show:
– The objects participating in the interaction
– The sequence of messages exchanged
288
Sequence Diagrams.
:Sistema
crearNuevaVenta()
*[más items]
descripción, total
:cajero
ingresarItem(codItem, cant)
finalizarVenta()
total con imptos.
realizarPago()
monto cambio, recibo
Bucle
Un diagrama de secuencia del sistema muestra, para un escenario particular de un caso de uso, los eventos externos que los actores generan, su orden y los eventos inter-sistemas.
289
Sequence Diagrams.
:JuegodeDados dado1:Dados dado2:Dados
jugar() lanzar()
val1:=getValorMostrado()
lanzar()
val2:=getValorMostrado()
290
Sequence Diagrams.
:Computer :PrintServer :Printer
print(arch) print(arch) [no queue]
print(arch)
291
Sequence Diagrams.
:Computer :PrintServer :Printer
print(arch) print(arch) [no queue]
print(arch)
Mensaje
Línea de vida
Activación
Mensaje Sincrónico
Retorno
Condición
Objetos participantes en la interacción
Puede omitirse
292
Sequence Diagrams.
:ItemWindow
:Item
NuevoItem(data)
crearItem(data)
Flecha hacia un objeto
índica creación del objeto.
:ItemWindow :Item EliminarItem()
BorrarItem() X
X indica destrucción del objeto
293
Sequence Diagrams.
Mensaje Simple / Sincrónico No se dan detalles de la comunicación cuando no
son conocidos o no son relevantes.
Mensaje Asincrónico
Sintaxis del mensaje: Número de secuencia [condición] * [expresión iteración]
valor de retorno := nombre del mensaje (parámetros)
Respuesta / Resultado
294
Sequence Diagrams.
a1:ClaseA b1:ClaseB
u Una ramificación es mostrada por múltiples mensaje que
abandonan un mismo punto, cada una etiquetada con una
condición
u Si las condiciones son mutuamente excluyentes representan
condiciones; de otra manera representan concurrencia.
:ClaseC [x>0] Op1()
X
[x<0] Op1()
295
Sequence Diagrams.
a1:Order b1:OrderLine
Sintaxis: * [expresión-iteación ] mensaje
*[for each] subtotal()
OrderTotal()
298
Sequence Diagrams.
Messages are arrows that represent
communication between objects.
Use half-arrowed lines to represent
asynchronous messages.
Asynchronous messages are sent
from an object that will not wait for a
response from the receiver before
continuing its tasks.
299
Sequence Diagrams.
Lifelines are vertical dashed
lines that indicate the object's
presence over time.
300
Sequence Diagrams.
Objects can be terminated
early using an arrow labeled
"< < destroy > >" that points to
an X.
301
Sequence Diagrams.
A repetition or loop within a
sequence diagram is depicted
as a rectangle. Place the
condition for exiting the loop at
the bottom left corner in
square brackets [ ].
310
Sequence Diagrams.
Follow these steps to create a sequence diagram. (These are
General guidelines; to write a sequence diagram you must
make sure you check for all interactions among all objects.)
1. Select a use case.
2. Add the first object in the use case to the diagram.
3. Add its method, the message it sends to the next object, and the next
object.
4. Check whether the second object replies to the first or sends on another
message and add the appropriate elements.
311
Sequence Diagrams.
5. Repeat steps 3 and 4 as necessary.
6. Add any necessary elements mentioned in this section such
as conditions, iteration markers, or object deletions.
314
Collaboration Diagrams.
GENERAR EL DIAGRAMA DE StECUENCIA PARA LA
MAQUINA RECICLADOR
• Alternative to Sequence diagrams
• Objects are connected with numbered arrows showing the flow of the
information
• Arrows are drawn from the source of the interaction
• The object towards with the arrow points is known as the target
• Arrows are numbered to show the order in which they are used within the
scenario
• Also marked with a description of the task required of the target object
319
• Group data objects of the same type.
• Declare arrays of primitive or class types:
char s[];
Point p[];
char[] s;
Point[] p;
• Create space for a reference.
• An array is an object; it is
created with new.
Declaring arrays.
320
• Use the new keyword to create an array object.
• For example, a primitive (char) array:
public char[] createArray() {
char[] s;
s = new char[26];
for ( int i=0; i<26; i++ ) {
s[i] = (char) (’A’ + i);
}
return s;
}
Declaring arrays.
321
• Initialize an array element
• Create an array with initial values:
String names[];
names = new String[3];
names[0] = "Georgianna";
names[1] = "Jen";
names[2] = "Simon";
String names[] = { "Georgianna","Jen","Simon"};
MyDate dates[];
dates = new MyDate[3];
dates[0] = new MyDate(22, 7, 1964);
dates[1] = new MyDate(1, 1, 2000);
dates[2] = new MyDate(22, 12, 1964);
MyDate dates[] = { new MyDate(22, 7, 1964),new MyDate(1, 1, 2000), new MyDate(22, 12,
1964) };
Initializing Arrays.
322
• Arrays of arrays:
int twoDim [][] = new int [4][];
twoDim[0] = new int[5];
twoDim[1] = new int[5];
int twoDim [][] = new int [][4]; illegal
Multidimensional Arrays.
325
• Non-rectangular arrays of arrays:
twoDim[0] = new int[2];
twoDim[1] = new int[4];
twoDim[2] = new int[6];
twoDim[3] = new int[8];
• Array of four arrays of five integers each:
int twoDim[][] = new int[4][5];
Multidimensional Arrays.
326
• All array subscripts begin at 0:
int list[] = new int [10];
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
Array Bounds.
327
• Cannot resize an array
• Can use the same reference variable to refer to an entirely new array:
int myArray[] = new int[6];
myArray = new int[10];
Array Resizing.
333
Single Inheritance
• When a class inherits from only one class, it is called single inheritance.
• Interfaces provide the benefits of multiple inheritance without drawbacks.
• Syntax of a Java class:
<modifier> class <name> [extends <superclass>] {
<declarations>*
}
336
Overriding Methods
• A subclass can modify behavior inherited from a parent class.
• A subclass can create a method with different functionality than the parent’s
method but with the same:
– Name
– Return type
– Argument list
338
The Super Keyword
• super is used in a class to refer to its superclass.
• super is used to refer to the members of superclass,both data attributes and
methods.
• Behavior invoked does not have
to be in the superclass; it can be
further up in the hierarchy.
339
Polymorphism
• Polymorphism is the ability to have many different forms; for example, the
Manager class has access to methods from Employee class.
• An object has only one form.
• A reference variable can refer to objects of different forms.
340
Virtual Method Invocation
• Virtual method invocation:
Employee e = new Manager();
e.getDetails();
• Compile-time type and runtime type
341
Rules About Overriding Methods
• Must have a return type that is identical to the method it overrides
• Cannot be less accessible than the method it overrides
342
Heterogeneous Collections
• Collections of objects with the same class type are called homogenous
collections.
MyDate[] dates = new MyDate[2];
dates[0] = new MyDate(22, 12, 1964);
dates[1] = new MyDate(22, 7, 1964);
• Collections of objects with different class types are called heterogeneous
collections.
Employee [] staff = new Employee[1024];
staff[0] = new Manager();
staff[1] = new Employee();
staff[2] = new Engineer();
344
Casting Objects
• Use instanceof to test the type of an object
• Restore full functionality of an object by casting
• Check for proper casting using the following guidelines:
– Casts up hierarchy are done implicitly.
– Downward casts must be to a subclass and checked by the compiler.
– The object type is checked at runtime when runtime errors can occur.
345
Overloading method names
• Use as follows:
– public void println(int i)
– public void println(float f)
– public void println(String s)
• Argument lists must differ.
• Return types can be different.
346
Overloading Constructors
• As with methods, constructors can be overloaded.
• Example:
public Employee(String name, double salary, Date DoB)
public Employee(String name, double salary)
public Employee(String name, Date DoB)
• Argument lists must differ.
• You can use the this reference at the first line of a constructor to call another
constructor.
348
The Object Class
• The Object class is the root of all classes in Java
• A class declaration with no extends clause, implicitly uses “extends the
Object”
public class Employee {
...
}
• is equivalent to:
public class Employee extends Object {
...
}
349
The == Operator Compared with the equals Method
• The == operator determines if two references are identical to each other (that
is, refer to the same object).
• The equals method determines if objects are “equal” but not necessarily
identical.
• The Object implementation of the equals method uses the == operator.
• User classes can override the equals method to implement a domain-specific
test for equality.
• Note: You should override the hashCodemethod if you override the equals
method.
350
The toString Method
• Converts an object to a String.
• Used during string concatenation.
• Override this method to provide information about a user-defined object in
readable format.
• Primitive types are converted to a String using the wrapper class’s toString
static method.
353
The Static Keyword
• The static keyword is used as a modifier on variables, methods, and nested
classes.
• The static keyword declares the attribute or method is associated with the
class as a whole rather than any particular instance of that class.
• Thus static members are often called “class members,” such as “class
attributes” or “class methods.”
354
Class Attributes
• Are shared among all instances of a class
• Can be accessed from outside the class without an instance of the class (if
marked as public)
355
Class Attributes
• You can invoke static method without any instance of the class to which it
belongs.
356
Static Initializers
• A class can contain code in a static block that does not exist within a method
body.
• Static block code executes only once, when the class is loaded.
• A static block is usually used to initialize static (class) attributes.
357
Abstract Classes
• An abstract class models a class of objects where the full implementation is
not known but is supplied by the concrete subclasses.
358
Interfaces
• A “public interface” is a contract between client code and the class that implements that interface.
• AJava interface is a formal declaration of such a contract in which all methods contain no implementation.
• Many unrelated classes can implement the same interface.
• A class can implement many unrelated interfaces.
• Syntax of a Java class:
<class_declaration> ::=
<modifier> class <name> [extends <superclass>]
[implements <interface> [,<interface>]* ] {
<declarations>*
}
361
Unit Objectives
After completing this unit, you should be able to:
Apply the concept of inheritance
Define a subclass and a superclass
Explain overriding methods
Describe the principle of dynamic binding
Explain polymorphism
Define abstract classes and interfaces
362
Review.
Classes in Java may have methods and attributes.
– Methods define actions that a class can perform.
– Attributes describe the class.
364
Review.
The phrase "to create an
instance of an object“ means
to create a copy of this object
in the computer's memory
according to the definition of
its class.
370
Inheritance.
• Is a mechanism for defining a new class in terms of an
existing class.
• Allows you to group related classes so that they can be
managed collectively.
• Promotes reuse.
• Allows you hide or override inherited methods.
• Relevant terms: generalization, specialization, override.
372
Inheritance.
Inheritance is often represented as a tree. Moving down the
tree, classes become more specialized, more honed toward
An application. Moving up the tree, classes are more
general;
they contain members suitable for many classes but are
often
not complete.
384
Dynamic Binding.
Dynamic Binding is when an operation and operands don't
find
each other until execution time.
Dynamic binding works with polymorphism and inheritance to
make systems more malleable.
Dynamic binding happens when the JVM resolves which
method to call at run time and is a form of polymorphism.
Dynamic binding is based on the type of the object, not the
type of the object reference.
392
Interfaces.
• Interfaces encapsulate a coherent set of services and
attributes, for example, a role.
• Objects in order to participate in various relationships,
need to state that they have the capability to fulfill a
particular role.
• All interfaces must have either public or default access.
• All methods (if any) in an interface are public, and
abstract (either explicitly or implicitly).
• All fields (if any) in an interface are public, static, and
final (either explicitly or implicitly).
397
• An exception is an event or condition that disrupts the normal flow of
execution in a program
– Exceptions are errors in a Java program
– The condition causes the system to throw an exception
– The flow of control is interrupted and a handler will catch the exception
• Exception handling is object-oriented
– It encapsulates unexpected conditions in an object
– It provides an elegant way to make programs robust
– It isolates abnormal from regular flow of control
Exceptions.
398
• A JVM can detect unrecoverable conditions
• –Examples:
– Class cannot be loaded
– Null object reference used
• Both core classes and code that you write can throw exceptions
• –Examples:
– IO error
– Divide by zero
– Data validation
• Business logic exception
• Exceptions terminate
execution unless they
are handled by the
program
Exceptions.
399
• Throwable is the base class, and provides a common interface and
implementation for most exceptions
• Error indicates serious problems that a reasonable application should not try
to catch, such as:
– VirtualMachineError
– CoderMalfunctionError
• Exception heads the class of conditions that should usually be either caught
or specified as thrown
• A RuntimeException can be thrown during the normal operation of the JVM
– Methods may choose to catch these but need not specify them as thrown
– Examples:
• ArithmeticException
• BufferOverflowException
The Exceptions Hierarchy
401
• Checked exceptions must be either handled in the method where they are
generated, or delegated to the calling method
Handling Exceptions
402
• throws
– –A clause in a method declaration that lists exceptions that may be
delegated up the call stack
• Example: public int doIt() throws SomeException, …
• try
– Precedes a block of code with attached exception handlers
– Exceptions in the try block are handled by the exception handlers
• catch
– A block of code to handle a specific exception
• finally
– An optional block which follows catch clauses
– Always executed regardless of whether an exception occurs
• throw
– Launches the exception mechanism explicitly
– Example: throw (SomeException)
Keywords
403
• To program exception handling, you must use try/catch blocks
• Code that might produce a given error is enclosed in a try block
• The catch clause must immediately follow the try block
try/catch blocks
404
• The clause always has one argument that declares the type of exception to be
caught
• The argument must be an object reference for the class Throwable or one of
its subclasses
• Several catch clauses may follow one try block
The catch clause
407
• Optional clause that allows cleanup and other operations to occur whether an
exception occurs or not
– –May have try/finally with no catch clauses
• Executed after any of the following:
– try block completes normally
– catch clause executes
• Even if catch clause includes return
– Unhandled exception is thrown, but before execution returns to calling
method
The finally clause
409
• It may be necessary to handle exceptions inside a catch or finally clause
– For example, you may want to log errors to a file, but all I/O operations
require IOException to be caught.
• Do this by nesting a try/catch (and optional finally) sequence inside your
handler
Nested Exception Handling
410
• Not to be confused with keyword throws
• Can be used in a try block when you want to deliberately throw an exception
• You can throw a predefined Throwable object or your own Exception subtype
• Create a new instance of the exception class to encapsulate the condition
• The flow of the execution stops immediately after the throw statement, and
the next statement is not reached
– A finally clause will still be executed if present
The throw keyword
411
• What happens when something goes wrong in the JVM?
– It throws an error derived from Error depending on the type of problem
• What happens if RuntimeException is thrown?
– Methods are not forced to declare RuntimeException in their throws
clauses; the exception is passed to the JVM
• The JVM does the necessary cleaning and terminates the application or applet
Handling runtime exceptions
412
• An assertion is a Java statement that allows you to test your assumptions
about your program
– In a traffic simulator, you might want to assert that a speed is positive,
yet less than a certain maximum
• An assertion contains a boolean expression that you believe will be true when
the assertion executes – if not true, the system throws an error
– By verifying that the boolean expression is true, the assertion confirms
your assumptions about the behavior of your program, increasing your
confidence that the program is free of errors
• Benefits:
– Writing assertions while programming is a quick and effective way to
detect and correct bugs
– Assertions document the inner workings of your program, enhancing
maintainability
Assertions
413
• Two forms:
– assert <boolean expression> ;
– assert <boolean expression> : <value expression> ;
• •If the boolean expression is false:
– Form 1 throws an AssertionError with no message
– Form 2 throws an AssertionError with a message defined by evaluating
the second expression
• •Assertion checking is disabled by default.
– Must be enabled at Java command line using the enableassertions switch
– Assertions can be enabled or disabled on a package-bypackage or class-by-
class basis
– assert statements are ignored if not enabled
Using assertions
414
• Do not use assertions:
– For argument checking in public methods
– To do any work that your application requires for correct operation
• Use assertions to test:
– Internal invariants (values that should not change)
• For example, place default: assert false at the end of switch statements with
no default
– Control-flow invariants
• For example, place assert false at locations that should never be reached
– Preconditions, postconditions, and class invariants
• For example, argument checking in private methods
When to use assertions
415
• Do not use assertions:
– For argument checking in public methods
– To do any work that your application requires for correct operation
• Use assertions to test:
– Internal invariants (values that should not change)
• For example, place default: assert false at the end of switch statements with
no default
– Control-flow invariants
• For example, place assert false at locations that should never be reached
– Preconditions, postconditions, and class invariants
• For example, argument checking in private methods
When to use assertions
417
Abstract Window Toolkit (AWT).
• Provides graphical user interface (GUI) components that are used in all Java
applets and applications.
• Contains classes that can be composed or extended. Classes can also be
abstract.
• Ensured that every GUI component that is displayed on the screen is a subclass
of the abstract class Component or MenuComponent.
• Has Container, which is an abstract subclass of Component and includes two
subclases:
»Panel
»Window
419
Containers.
• Add components with the add methods.
• The two main types of containers are Window and Panel.
• A Windows is a free floating window on the display.
• A Panel is a container of GUI components that must exists in the context of
some other container, such as a window or applet.
421
The Component class.
• The Component class defines the attributes and behavior common to all visual
components used in the user interface. It is an abstract class. It also defines
the way in which applications and applets can interact with users by capturing
events.
422
Frames.
• Are a subclass of Window
• Have title and resizing corners
• Are initially invisible, use setVisible(true) to expose the frame
• Have BorderLayout as the default layout manager
• Use the setLayout method to change the default layout manager.
Frame inherits its characteristics from the Container class so you can add
Components to a frame using the add method.
429
The Panel Class.
The Panel class is a container on which components can be
placed.
After you create a Panel, you must add it to a Window or
Frame. This is done using the add method of the Container
class. Then set the frame to be visible so that the frame and
panel are displayed.
434
The FlowLayout Manager.
Default layout for the Panel class.
Components added from
left to right
Default alignment is centered
Uses components’
preferred sizes
Uses the constructor to
tune behavior
438
The BorderLayout Manager.
Default layout for the Frame class
Components added to specific regions.
443
The GridLayout Manager.
• Components are added left to right, top to bottom.
• All regions are equally sized.
• The constructor specifies the rows and columns.
449
What is an Event?
• Events – Objects that describe what happened
– Event sources – The generator of an event
– Event handlers – A method that receives an event object, deciphers it, and
processes the user’s interaction
450
What is an Event?
• An event can be sent to many event handlers.
• Event handlers register with components when they are interested in events
generated by that component.
451
Delegation Model
• Client objects (handlers) register with a GUI component they want to observe.
• GUI components only trigger the handlers for the type of event that has
occurred.
• Most components can trigger more than one type of event.
• Distributes the work among multiple classes.
452
Multiple listeners
• Multiple listeners cause unrelated parts of a program to react to the same
event.
• The handlers of all registered listeners are called when the event occurs.
• The listener classes that you define can extend adapter classes and override
only the methods that you need.
454
How to create a menu.
1. Create a MenuBar object, and set it into a menu container, such as a Frame.
2. Create one or more Menu objects, and add them to the menu bar object.
3. Create one or more MenuItem objects, and add them to the menu object.
460
• On most computer systems, simple programs are run as processes by the CPU
• A process runs in its own memory address space, and consists of data, a call
stack, the code being executed, the heap and other segments
• A thread executes instructions and is a path of execution through a program
(process)
– A thread does not carry all of the process information data
– Many threads may run concurrently through a program, and may
potentially share and access the same global data within the program
Processes and Threads.
461
Threads in Java.
• Java has several classes that enable threads to be created
• The Runnable interface defines a single method: run().
• The Thread class implements the Runnable interface and adds methods to
manage the thread’s priority, interrupt the thread, temporarily suspend the
thread and so on.
• The java.lang.Thread class is the base for all objects that can behave as
threads
462
Create Threads in Java.
• There are two ways to create a new thread using the Thread class
• A class can subclass Thread and override the run() method of the Thread class
– The Thread itself is a Runnable object
• A class can implement the Runnable interface and implement the run method
– This class can be run as a thread by creating a new Thread object and
passing the Runnable object into the Thread(Runnable) constructor
– New activities are started when the Thread object executes the Runnable
object’s run() method
463
Example: subclassing the Thread class.
The class TrafficLight extends the Thread class and overrides the inherited
method run():
class TrafficLight extends Thread {
public void run() {
// loop, change light color & sleep
}
}
Run the thread using the start() method inherited from the Thread class:
...
TrafficLight tl = new TrafficLight();
t1.start(); // Indirectly calls run()
...
464
Example: subclassing the Thread class.
The class TrafficLight has to provide its implementation for the method run():
class TrafficLight implements Runnable {
public void run() {
// loop, change light color & sleep
}
}
Create a new Thread with the Runnable class as a parameter:
...
TrafficLight tl = new TrafficLight();
new Thread(tl).start();
...
466
Life cycle of a Thread.
• A thread that is running or asleep is said to be alive
– This can be tested with the isAlive() method
• Once dead, the thread cannot be restarted
– –However, it can be examined
467
Controlling Activities.
• Threads are meant to be controlled
– Methods exist to tell a thread when to run, when to pause,and so forth
– start() - starts the thread's run() method
– sleep() – pauses execution for given amount of time
– stop() - deprecates since it is inherently unsafe
– destroy() - kills a thread without any cleanup
– resume()and suspend() - deprecates for the same reason as stop()
– yield() - causes the currently executing thread object to pause
temporarily, and allow other threads to execute
– interrupt() - causes any kind of wait or sleep to be aborted
– setPriority() - updates the priority of this thread
468
Stopping Threads.
• When the run() method returns, the thread is dead
– A dead thread cannot be restarted
• A dead Thread object is not destroyed
– Its data can be accessed
• Set a field to indicate stop condition and poll it often
public void run() {
stopFlag = false;
try {
while (!stopFlag) {......}
}
catch (InterruptedException e) {...}
}
public void finish() {
stopFlag = true;
.........
}
470
Daemon Threads.
• Daemon threads are service threads that run in the background
• Daemon threads are commonly used to:
– Implement servers polling sockets
– Loop waiting on an event or input
– Service other threads
• Since daemon threads exist to support other threads, the JVM terminates a
program when no user threads are running and only daemon threads remain
• Applicable control methods on a thread:
– isDaemon() – check the daemon status of a thread
– setDaemon() – set the daemon status of a thread
471
Multi-Threading: need for synchronization
• In many situations, concurrently running threads must share data and consider
the state and activities of other threads
– Example: producer-consumer programming scenarios
• Producer thread generates data that is needed and consumed by another
thread
– Data may be shared using a common object that both threads access
• In Java, an object can be operated on by multiple threads; it is the
responsibility of the object to protect itself from any possible interference
• Objects can be locked to prevent critical sections of code from being
simultaneously accessed by multiple threads
472
Multi-Threading: need for synchronization
• The synchronized keyword may be used to synchronize access to an object
among the threads using the object
– The synchronized keyword guards critical sections of code
– Either methods or arbitrary sections of code may be synchronized
473
Multi-Threading: need for synchronization
• All synchronized sections of code in an object are locked when a thread
executes any one synchronized code section
– No other threads are able to enter a synchronized section of code while it
is locked
– Threads may still access other non-synchronized methods
• If the synchronized method is static, a lock is obtained at the class level
instead of the object level
– Only one thread at a time may use such a method
476
Synchronization issues
• Use synchronization sparingly
– Can slow performance by reducing concurrency
– Can sometimes lead to fatal conditions such as deadlock
• Other techniques should be used with synchronization to assure optimal
performance and to assist threads in coordinating their activities
– For example, notifyAll() and wait()
478
What Is a Stream?.
Java programs perform I/0 through streams. A stream is an
abstraction that either produces or consumes information.
A stream is linked to a physical device by the Java I/O system.
480
What Is a Stream?.
Java implements streams within
class hierarchies defined in the
java.io package.
Byte streams provides a convenient
means for handling input and output
bytes.
Characters streams are designed for handling the input and
output of characters.
495
Microsoft® SQL Server™ es una base de datos
relacional cliente-servidor basada en el Lenguaje
de consulta estructurado (SQL, Structured Query
Language).
496
Base de datos.
Una base de datos es similar a un archivo de datos
en cuanto a que ambos son un almacenamiento de
datos.
Como en un archivo de datos, una base de datos
presenta información directamente al usuario; el
usuario ejecuta una aplicación que tiene acceso a
los datos de la base de datos y los presenta al
usuario en un formato inteligible.
497
Base de datos.
En una base de datos los elementos de datos están
agrupados en una única estructura o registro, y se
pueden definir relaciones entre dichas estructuras y
registros.
En una base de datos bien diseñada, no hay
elementos de datos duplicados que el
usuario o la aplicación tengan que actualizar al
mismo tiempo.
498
Base de datos.
Una base de datos suele tener dos componentes:
• Los archivos que almacenan la base de datos
física.
• El software del sistema de administración de la
base de datos (DBMS, Database Management
System).
499
Base de datos.
El DBMS es el responsable de mantener la
estructura de la base de datos, lo que incluye:
• El mantenimiento de las relaciones entre los
datos de la base de datos.
• La garantía de que los datos estén correctamente
almacenados y de que no se infrinjan las reglas
que definen las relaciones entre los datos.
• La recuperación de todos los datos hasta un
punto coherente en caso de fallos del sistema.
500
Base de datos relacional.
Los sistemas de bases de datos relacionales son
una aplicación de la teoría matemática de los
conjuntos al problema de la organización de los
datos.
En una base de datos relacional, los datos
están organizados en tablas (llamadas relaciones en
la teoría relacional).
501
Base de datos relacional (Tablas).
Una tabla representa una clase de objeto que tiene
cierta importancia en una organización.
Por ejemplo,una corporación puede tener una base
de datos con una tabla para los empleados, otra
tabla para los clientes y otra para los productos del
almacén.
502
Base de datos relacional (Tablas).
Las tablas están compuestas de columnas y filas
(atributos y tuplas en la teoría relacional).
id nombre Descripción tamaño
300 Camisa Cuello V Ch
301 Camisa Ovalada M
302 Camisa Manga Corta S
Atributos
Columna Tupla, fila
503
Cliente-servidor.
En los sistemas cliente-servidor, el servidor es un
equipo relativamente grande situado en una
ubicación central que administra recursos utilizados
por varios individuos.
Cuando los individuos tienen que utilizar un recurso,
se conectan con el servidor desde sus equipos, o
clientes, a través de la red.
504
Cliente-servidor.
En la arquitectura cliente-servidor de las bases de
datos, los archivos de la base de datos y software
DBMS residen en el servidor. Se proporcionan
componentes de comunicaciones para que las
aplicaciones se puedan ejecutar en equipos cliente y
se comuniquen con el servidor de bases de datos a
través de la red. El componente de comunicación de
SQL Server también permite la comunicación entre
una aplicación que se ejecute en el servidor y SQL
Server.
505
Cliente-servidor.
Las aplicaciones del servidor suelen poder trabajar
con varios clientes al mismo tiempo. SQL Server
puede operar con miles de aplicaciones cliente
simultáneas.
El servidor tiene funciones que impiden que se
produzcan problemas de lógica si un usuario
intenta leer o modificar los datos actualmente
utilizados por otros usuarios.
507
Lenguaje de consulta estructurado (SQL).
Para trabajar con los datos de una base de datos,
tiene que utilizar un conjunto de comandos e
instrucciones (lenguaje) definidos por el software del
DBMS.
En las bases de datos relacionales se pueden
utilizar distintos lenguajes, el más común es SQL.
508
Lenguaje de consulta estructurado (SQL).
Los estándares de SQL han sido definidos por el
American National Standards Institute (ANSI) y la
International Standards Organization (ISO).
La mayor parte de los productos DBMS modernos
aceptan el nivel básico de SQL-92, el último
estándar de SQL (publicado en 1992).
509
Componentes de una base de datos.
Una base de datos SQL Server consiste en una
colección de tablas que guardan conjuntos
específicos de datos estructurados.
Una tabla (entidad) contiene una colección de filas
(tuplas) y columnas (atributos).
Cada columna en la tabla se diseña para guardar un
cierto tipo de información (por ejemplo, fechas,
nombres, montos, o números).
510
Componentes de una base de datos.
Las tablas tienen varios tipos de controles
(restricciones, reglas, desencadenadores, valores
por defecto, y tipos de datos de usuario) que
aseguran la validez de los datos.
Las tablas pueden tener índices (similar a los de los
libros) que permiten encontrar las filas rápidamente.
511
Componentes de una base de datos.
Usted puede agregar restricciones de integridad
referencial a las tablas para asegurar la
consistencia entre los datos interrelacionados en
tablas diferentes.
512
Componentes de una base de datos.
Una base de datos también puede utilizar
procedimientos almacenados que usan Transact-
SQL programando código para realizar operaciones
con los datos en la base de datos, como guardar
vistas que proporcionan acceso personalizado a los
datos de la tabla.
514
SQL Modelo lógico Representación
Física
Tabla Entidad Archivo
Columna Atributo Campo
Renglón Instancia Registro
Llave Primaria (PK) Llave Primaria
Llave Foránea (FK) Llave Foránea
515
Normalización.
Al organizar los datos en tablas, se pueden
encontrar varias formas de definirlas.
La teoría de las bases de datos relacionales define
un proceso, la normalización, que asegura que el
conjunto de tablas definido organizará los datos de
manera eficaz.
516
Normalización.
En la teoría de diseño de base de datos
relacionales, las reglas de normalización identifican
ciertos atributos que deben estar presentes o
ausentes en una base de datos bien diseñada.
Una tabla debe tener un identificador, debe guardar
datos para sólo un solo tipo de entidad, debería
evitar columnas que acepten valores nulos, y no
debe tener valores o columnas repetidas.
517
Una Tabla debe Tener un Identificador
Cada tabla debe tener un identificador de las filas,
que es una columna o un conjunto de columnas que
toman valores únicos para cada registro de la tabla.
Cada tabla debe tener una columna de ID, y ningún
registro puede compartir el mismo valor de ID con
otro.
518
Una Tabla debe Tener un Identificador
La columna (o columnas) que sirve como
identificador único de la fila para una tabla
constituye la clave primaria de la tabla.
520
Cada columna tiene un nombre y tamaño específico.
Contiene datos referentes a un aspecto del tema de
la tabla. (Un atributo de la entidad).
Contiene datos de un tipo particular.
En MS-SQLServer se emplean tipos de datos como:
integer, char, varchar, float, money,date, etc.
521
id nombre Descripción tamaño
300 Camisa Cuello V Ch
301 Camisa Ovalada M
302 Camisa Manga Corta S
303 Playera L
Columna
Columna
Not Null
Columna
Null
Columna
Identity
522
El valor Null significa que la columna acepta que no
se le asignen valores.
Si la columna tiene un Not Null significa que debe
insertarse un valor en esta columna, de lo contrario
el renglón no será insertado.
Identity se usa para generar números secuenciales.
523
Una Tabla debe Evitar Columnas que acepten
valores nulos.
Las tablas pueden tener columnas definidas para
permitir valores nulos.
Un valor nulo indica que el registro no tiene valor por
ese atributo.
524
Una Tabla debe Evitar Columnas que acepten
valores nulos.
Aunque puede ser útil permitir valores nulos en
casos aislados, es mejor usarlos muy poco porque
ellos requieren un manejo especial con el
consiguiente aumento de la complejidad de las
operaciones de datos.
525
Una Tabla debe Evitar Columnas que acepten
valores nulos.
Si tiene una tabla que tiene varias columnas que
permiten valores nulos y varias de las filas tienen
valores nulos en dichas columnas, debería
considerar poner estas columnas en otra tabla
vinculada a la tabla primaria.
526
Una Tabla debe Evitar Columnas que acepten
valores nulos.
Guardar los datos en dos tablas separadas permite
que la tabla primaria sea simple en su diseño pero a
la vez mantener la capacidad de almacenar
información ocasional.
527
Una Tabla no Debe tener Valores o Columnas
Repetidas
Una tabla no debe contener una lista de valores
para un pedazo específico de información.
529
Definición de objetos de una base de datos.
CREATE object_name.
ALTER object_name.
DROP object_name.
531
Para crear una tabla.
Create Table <Table_Name>
(
Column_Name tipoDeDato (identity | Null | Not
Null),
[...más columnas separadas por comas...]
)
532
Ejemplo:
CREATE TABLE empleado
(
empID numeric(10,0) identity,
nombre varchar(30) not null,
apPaterno varchar(30) not null,
apMaterno varchar(30) null
)
Nombre de
Columna
Tipo de
Dato
Null o
Not Null
533
Agregando y eliminando columnas.
La instrucción ALTER TABLE se usa para agregar o
borrar columnas sobre una tabla.
AGREGAR COLUMNAS
ALTER TABLE tabla
ADD nombre_columna <tipo> [NULL | NOT NULL]
534
Agregando y eliminando columnas.
ELIMINAR COLUMNAS
ALTER TABLE tabla
DROP nombre_columna <tipo> [NULL | NOT NULL]
535
Agregando y eliminando columnas.
ALTER TABLE empleado
ADD rfc char(10) null
ALTER TABLE empleado
DROP COLUMN apMaterno
empID nombre apPaterno apMaterno rfc
537
AGREGAR DATOS.
La instrucción INSERT permite agregar datos a una
Tabla. Se debe usar una instrucción INSERT por
cada renglón a agregar en la tabla.
EJEMPLO:
INSERT INTO empleado
VALUES(‘Juan’,’Perez’,’Perez’)
538
RECUPERAR DATOS.
La cláusula SELECT es usada para la recuperación
de renglones y columnas de una tabla.
Las palabras principales que componen esta
instrucción son: SELECT, FROM, WHERE.
SELECT.- Especifica las columnas que se van a
desplegar en la consulta.
539
RECUPERAR DATOS.
FROM.- Especifica la tabla o las tablas donde se
encuentran almacenados los datos.
WHERE.- Especifica los renglones que se van a
desplegar.
EJEMPLO:
SELECT *
FROM empleado
540
RECUPERAR DATOS.
SELECT nombre
FROM empleado
SELECT nombre,apPaterno,apMaterno
FROM empleado
SELECT nombre,apPaterno
FROM empleado
WHERE nombre=‘Juan’
541
ACTUALIZAR DATOS.
La instrucción UPDATE cambia los datos existentes
En una tabla.
Se utiliza para actualizar un renglón, un grupo de
renglones o toda la tabla.
La cláusula UPDATE opera sobre una sola tabla.
542
ACTUALIZAR DATOS.
UPDATE empleado
SET apMaterno=‘el mismo para todos’
UPDATE empleado
SET nombre=‘Raul’
WHERE nombre=‘Juan’
543
ELIMINANDO DATOS.
La instrucción DELETE se usa para eliminar datos
de una tabla.
EJEMPLO:
DELETE FROM empleado
WHERE nombre=‘Raul’
544
RESTRICCIONES (CONSTRAINTS).
Para diseñar las tablas, es necesario identificar los
valores válidos para una columna y decidir cómo se
debe exigir la integridad de los datos de la columna.
Microsoft® SQL™ Server proporciona varios
mecanismos para exigir la integridad de los datos de
una columna:
545
RESTRICCIONES (CONSTRAINTS).
• Las restricciones de clave principal (PRIMARY
KEY).
• Las restricciones de clave externa (FOREIGN
KEY).
• Las restricciones de no duplicados (UNIQUE).
• Las restricciones de comprobación (CHECK).
• Las definiciones de valores predeterminados
(DEFAULT).
• La aceptación de NULL
546
RESTRICCIONES DE CLAVE PRINCIPAL.
Una tabla suele tener una columna o una
combinación de columnas cuyos valores identifican
de forma única a cada fila de la tabla. Estas
columnas se denominan claves principales de la
tabla y exigen la integridad de entidad de la tabla.
Puede crear una clave principal mediante la
definición de una restricción PRIMARY KEY cuando
cree o modifique una tabla.
547
RESTRICCIONES DE CLAVE PRINCIPAL.
Una tabla sólo puede tener una restricción
PRIMARY KEY, y ninguna columna a la que se
aplique una restricción PRIMARY KEY puede
aceptar valores Null.
Dado que las restricciones PRIMARY KEY aseguran
que los datos sean exclusivos, suelen definirse para
la columna de identidad.
548
RESTRICCIONES DE CLAVE PRINCIPAL.
CREATE TABLE Autores
(
AutorID not null,
Nombre not null,
Apellido not null,
AñoNac null,
AñoMuerte null,
Descripcion null
)
Tabla sin llave primaria
549
RESTRICCIONES DE CLAVE PRINCIPAL.
CREATE TABLE Autores
(
AutorID not null,
Nombre not null,
Apellido not null,
AñoNac null,
AñoMuerte null,
Descripcion null,
CONSTRAINT autor_pk PRIMARY KEY(AutorID)
)
Tabla con llave primaria
Nombre de la llave primaria
550
RESTRICCIONES DE CLAVE EXTERNA.
Una clave externa (FK) es una columna o una
combinación de columnas que se utiliza para
establecer y exigir un vínculo entre los datos de dos
tablas distintas.
Se crea un vínculo entre dos tablas mediante la
adición en una tabla de la columna o columnas que
contienen los valores de la clave principal de la otra
tabla. Esta columna se convierte en una clave
externa en la segunda tabla.
551
RESTRICCIONES DE CLAVE EXTERNA.
Puede crear una clave externa mediante la
definición de una restricción FOREIGN KEY cuando
cree o modifique una tabla. Ejemplo:
CREATE TABLE LibroEstado (
CondicionID int not null,
NombreCond varchar(14) not null,
Descripcion varchar(30) null,
CONSTRAINT cond_pk PRIMARY KEY(CondicionID)
)
552
RESTRICCIONES DE CLAVE EXTERNA.
CREATE TABLE Libros (
LibroID char(8) not null,
Titulo varchar(60) not null,
Editor varchar(60) null,
FechaEd date null,
Costo float not null,
CondicionID int not null,
Vendido char(2) null
)
Tabla sin FK
CondicionID no tiene ninguna
celación con el otro nombre de
Columna de la tabla
LibroEstado
553
RESTRICCIONES DE CLAVE EXTERNA.
CREATE TABLE Libros (
LibroID char(8) not null,
Titulo varchar(60) not null,
Editor varchar(60) null,
FechaEd datetime null,
Costo float not null,
CondicionID int not null,
Vendido char(2) null,
CONSTRAINT libro_pk PRIMARY KEY(CondicionID),
FOREIGN KEY(CondicionID) REFERENCES
LibroEstado(CondicionID)
)
Tabla con FK
DE LA TABLA
LIBROESTADO
554
RESTRICCIONES UNIQUE.
Puede utilizar restricciones UNIQUE para asegurar
que no se escriban valores duplicados en columnas
específicas que no formen parte de una clave
principal.
Aunque tanto una restricción de no duplicados como
de clave principal exigen que los elementos sean
únicos, es preferible utilizar una restricción UNIQUE
en vez de una restricción PRIMARY KEY cuando
desee exigir la unicidad de:
555
RESTRICCIONES UNIQUE.
• Una columna o una combinación de columnas
que no sea la clave principal. En una tabla se
puede definir varias restricciones UNIQUE, pero
sólo puede definirse una restricción PRIMARY
KEY.
• Una columna que acepte valores Null.
556
RESTRICCIONES UNIQUE.
Ejemplo:
CREATE TABLE LibroEstado (
CondicionID int not null,
NombreCond varchar(14) not null
UNIQUE NONCLUSTERED,
Descripcion varchar(30) null,
CONSTRAINT cond_pk PRIMARY KEY(CondicionID),
)
557
RESTRICCIONES UNIQUE.
Ejemplo:
CREATE TABLE LibroEstado (
CondicionID int not null,
NombreCond varchar(14) not null
UNIQUE NONCLUSTERED,
Descripcion varchar(30) null,
CONSTRAINT cond_pk PRIMARY KEY(CondicionID),
)
558
RESTRICCIONES CHECK.
Las restricciones de comprobación (CHECK) exigen
la integridad del dominio mediante la limitación de
los valores que puede aceptar una columna.
Puede crear una restricción CHECK con cualquier
expresión lógica (booleana) que devuelva TRUE
(verdadero) o FALSE (falso) basándose en
operadores lógicos.
559
RESTRICCIONES CHECK.
Es posible aplicar varias restricciones CHECK a una
sola columna. Estas restricciones se evalúan en el
orden en el que fueron creadas. También es posible
aplicar una sola restricción CHECK a varias
columnas si se crea al final de la tabla.
560
RESTRICCIONES CHECK.
CREATE TABLE Libros (
LibroID char(8) not null,
Titulo varchar(60) not null,
Editor varchar(60) null,
FechaEd datetime null,
Costo float not null CHECK(Costo>0),
CondicionID int not null,
Vendido char(2) null,
CONSTRAINT libro_pk PRIMARY KEY(CondicionID),
FOREIGN KEY(CondicionID) REFERENCES
LibroEstado(CondicionID)
)
Restricción check
561
RESTRICCIONES DEFAULT.
Cada columna de un registro debe contener un
valor, aunque ese valor sea NULL.
Puede haber situaciones en las que necesite cargar
una fila de datos en una tabla pero no conozca el
valor de una columna o el valor ya no exista.
Si la columna acepta valores NULL, puede cargar la
fila con un valor NULL.
562
RESTRICCIONES DEFAULT.
Pero, dado que puede no resultar conveniente
utilizar columnas que acepten valores NULL, una
mejor solución podría ser establecer una definición
DEFAULT para la columna donde corresponda.
Por ejemplo, es corriente especificar el valor cero
como valor predeterminado para las columnas
numéricas, o N/D (no disponible) como valor
predeterminado para las columnas de cadenas
cuando no se especifica ningún valor.
563
RESTRICCIONES DEFAULT.
CREATE TABLE Empleado(
EmpleadosID int not null,
Nombre varchar(60) not null,
...
...
FechaIng varchar(60) null, DEFAULT(getDate()),
...
CONSTRAINT emp_pk PRIMARY
KEY(EmpleadosID),
)
566
SQL es un lenguaje de manipulación de bases de datos
relacionales.
Las sentencias SQL se dividen en dos grupos:
• DDL (Data Definition Language).
• DML (Data Manipulation Language).
Bases de Datos Relacionales.
567
1. Crear en el DBMS la BD EjemploBD.
2. En la base de datos EjemploBD crear:
CREATE TABLE CLIENTE(
nombreCliente varchar(60) NOT NULL,
ocupacion varchar(60) NULL,
CONSTRAINT PK1 PRIMARY KEY
NONCLUSTERED (nombreCliente)
)
Bases de Datos Relacionales.
568
3. Configurar el DSN del usuario y del sistema con el
nombre lógico EjemploJava.
Bases de Datos Relacionales.
569
AÑADIR DATOS.
INSERT INTO CLIENTE(“Raul Oramas”,”profesor”);
INSERT INTO CLIENTE(“Juan Perez”,null);
INSERT INTO CLIENTE (nombreCliente,ocupacion)
VALUES(“El gato con botas”,”actor”);
Insertar 10 registros con ocupaciones de profesor,
estudiante y actor.
Bases de Datos Relacionales.
570
CONSULTAR DATOS.
SELECT * FROM CLIENTE
SELECT nombreCliente, ocupacion FROM CLIENTE
SELECT nombreCliente FROM CLIENTE
SELECT nombreCliente FROM CLIENTE
WHERE ocupacion=“profesor”
Bases de Datos Relacionales.
571
BORRAR DATOS.
DELETE FROM Cliente
Where ocupacion=“estudiante”
DELETE FROM Cliente
Bases de Datos Relacionales.
572
MODIFICAR DATOS.
UPDATE Cliente
SET ocupacion=“estudiante”
WHERE ocupacion=“actor”
UPDATE Cliente
SET ocupacion=“actor”
WHERE nombreCliente=“Juan Perez”
Bases de Datos Relacionales.
574
Una aplicación Java que realiza accesos a bases de datos
funciona según una arquitectura que permite escribir
los programas abstrayéndose de los detalles de los
niveles inferiores (discos, drivers, sistema operativo,
etc.)
En la siguiente figura se muestran los niveles más
importantes. En el nivel superior se encuentran las
aplicaciones que realizamos; estas aplicaciones son
interpretadas por la máquina virtual Java (JVM).
Arquitectura de la aplicación.
576
El sistema operativo proporciona el nivel de
entrada/salida, que interactúa con los dispositivos
físicos donde se encuentran las bases de datos.
El sistema operativo también administra el nivel de
ODBC (Open Data Base Conectivity).
ODBC nos permite utilizar una interfaz única para los
distintos tipos de bases de datos, además de
proporcionar nombres lógicos que se relacionan con los
nombres físicos que tendrán los archivos.
Arquitectura de la aplicación.
577
El siguiente gráfico muestra la arquitectura del sistema
de vista desde el nivel de aplicación, usando Java.
Arquitectura de la aplicación.
578
El “tubo” que se
ha dibujado
representa a la clase
Connection, que nos
proporciona el “medio”
para comunicarnos con
las bases de datos.
Según sea el tipo de la base de datos, los drivers serán
diferentes, por lo que en primer lugar creamos un
objeto de tipo DriverManager y, a través de él, el objeto
Connection.
Arquitectura de la aplicación.
579
Una vez que disponemos de la conexión adecuada, el
funcionamiento es muy simple: creamos una instancia
de la clase Statement y la utilizamos para definir las
sentencias SQL adecuadas en nuestra aplicación.
Arquitectura de la aplicación.
580
Estas sentencias SQL proporcionarán, en general, una
serie de datos provenientes de la base de datos, que se
almacenan en una instancia del objeto ResultSet.
Arquitectura de la aplicación.
582
Para poder acceder desde el nivel de aplicación a una
base de datos ya existente, debemos administrar los
orígenes de datos ODBC.
Debemos configurar el nombre lógico de la Base de
datos con “EjemploJava”.
A continuación se presenta la clase PruebaConexion, en
la que estableceremos una conexión a la base de datos
que previamente hemos preparado en el administrador
de ODBC.
Conexión a una base de datos.
583
01: // PruebaConexion.java 02: import java.sql.*; 03: public class PruebaConexion { 04: public static void main(String[] args) { 05: try { 06: Class.forName("sun.jdbc.odbc.jdbcOdbcDriver"); 07: String bd = "jdbc:odbc:EjemploJava"; 08: Connection conexion = DriverManager.getConnection(bd,"sa",null); 09:
Conexión a una base de datos.
Las clases e interfaces que utilizaremos se encuentran en el
paquete java.sql
584
01: // PruebaConexion.java 02: import java.sql.*; 03: public class PruebaConexion { 04: public static void main(String[] args) { 05: try { 06: Class.forName("sun.jdbc.odbc.jdbcOdbcDriver"); 07: String bd = "jdbc:odbc:EjemploJava"; 08: Connection conexion = DriverManager.getConnection(bd,"sa",null); 09:
Conexión a una base de datos.
Primero establecemos el driver a utilizar (ODBC) que nos
proporciona la biblioteca JDBC.
585
01: // PruebaConexion.java 02: import java.sql.*; 03: public class PruebaConexion { 04: public static void main(String[] args) { 05: try { 06: Class.forName("sun.jdbc.odbc.jdbcOdbcDriver"); 07: String bd = "jdbc:odbc:EjemploJava"; 08: Connection conexion = DriverManager.getConnection(bd,"sa",null); 09:
Conexión a una base de datos.
Para crear la conexión, establecemos la fuente de donde
provienen los datos. Utilizaremos el nombre lógico que
habíamos preparado en el administrador de ODBC.
586
01: // PruebaConexion.java 02: import java.sql.*; 03: public class PruebaConexion { 04: public static void main(String[] args) { 05: try { 06: Class.forName("sun.jdbc.odbc.jdbcOdbcDriver"); 07: String bd = "jdbc:odbc:EjemploJava"; 08: Connection conexion = DriverManager.getConnection(bd,"sa",null); 09:
Conexión a una base de datos.
Hacemos uso del método getConnection perteneciente a la clase
DriverManager, aplicado al nombre lógico de la fuente de datos.
587
10: Statement sentenciaSQL = conexion.createStatement(); 11: ResultSet clientes = sentenciaSQL.executeQuery("SELECT * FROM CLIENTE"); 12: 13: clientes.close(); 14: conexion.close(); 15: sentenciaSQL.close(); 16: } 17: catch (ClassNotFoundException e) { 18: System.out.println("Clase no encontrada"); 19: } 20: catch (SQLException e) { 21: System.out.println(e); 22: } 24: } 25:}
Conexión a una base de datos.
Utilizando el método createStatement, perteneciente al objeto de
tipo Connection, creamos el objeto de tipo Statement.
588
10: Statement sentenciaSQL = conexion.createStatement(); 11: ResultSet clientes = sentenciaSQL.executeQuery("SELECT * FROM CLIENTE"); 12: 13: clientes.close(); 14: conexion.close(); 15: sentenciaSQL.close(); 16: } 17: catch (ClassNotFoundException e) { 18: System.out.println("Clase no encontrada"); 19: } 20: catch (SQLException e) { 21: System.out.println(e); 22: } 24: } 25:}
Conexión a una base de datos.
Ya estamos en condiciones de obtener los datos deseados de la
BD: nos basta con crear un objeto de tipo ResultSet.
589
10: Statement sentenciaSQL = conexion.createStatement(); 11: ResultSet clientes = sentenciaSQL.executeQuery("SELECT * FROM CLIENTE"); 12: 13: clientes.close(); 14: conexion.close(); 15: sentenciaSQL.close(); 16: } 17: catch (ClassNotFoundException e) { 18: System.out.println("Clase no encontrada"); 19: } 20: catch (SQLException e) { 21: System.out.println(e); 22: } 24: } 25:}
Conexión a una base de datos.
En las líneas 13 a 15 se realiza una liberación explícita de los
recursos empleados, utilizando los métodos close.
590
10: Statement sentenciaSQL = conexion.createStatement(); 11: ResultSet clientes = sentenciaSQL.executeQuery("SELECT * FROM CLIENTE"); 12: 13: clientes.close(); 14: conexion.close(); 15: sentenciaSQL.close(); 16: } 17: catch (ClassNotFoundException e) { 18: System.out.println("Clase no encontrada"); 19: } 20: catch (SQLException e) { 21: System.out.println(e); 22: } 24: } 25:}
Conexión a una base de datos.
En las líneas 17 al 22 se recogen las excepciones que podrían levantarse
debido a las instanciaciones realizadas y a los métodos invocados.
592
Los objetos ResultSet permiten recoger los resultados
de la ejecución de consultas SQL; estos resultados
proporcionan un número variable de columnas y de
filas.
ResultSet es un contenedor tabular de tamaño variable.
Consultas y ResultSet.
593
import java.sql.*; public class Listado { public static void main(String args[]) { String nombreCliente,ocupacion; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String bd = "jdbc:odbc:EjemploJava"; Connection conexion = DriverManager.getConnection(bd,"sa",null); Statement sentenciaSQL = conexion.createStatement();
Consultas y ResultSet.
594
ResultSet cliente = sentenciaSQL.executeQuery("SELECT * from cliente"); while (cliente.next()) { nombreCliente = cliente.getString("nombreCliente"); ocupacion = cliente.getString(2); System.out.println("**********"); System.out.println(nombreCliente + "\t" + ocupacion); System.out.println("**********"); }
Consultas y ResultSet.
595
cliente.close(); conexion.close(); sentenciaSQL.close(); } catch (ClassNotFoundException e) { System.out.println("Clase no encontrada"); } catch (SQLException e ) { System.out.println(e); } } }
Consultas y ResultSet.
597
import java.sql.*; public class Modificar { public static void main(String args[]) { String nombreCliente,ocupacion; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String bd = "jdbc:odbc:EjemploJava"; Connection conexion = DriverManager.getConnection(bd,"sa",null);
nombreCliente = "Pedro Rosas"; ocupacion = "Paletero"; String sqlTexto = "UPDATE CLIENTE + "SET ocupacion = '"+ocupacion" +" WHERE nombreCliente='"+nombreCliente+"'"; Statement sentenciaSQL = conexion.createStatement(); int renglonesAfectados = sentenciaSQL.executeUpdate(sqlTexto);
Actualizaciones.
598
if(renglonesAfectados==1) { System.out.println("Datos modificados"); } else System.out.println(sqlTexto); conexion.close(); sentenciaSQL.close(); } catch (ClassNotFoundException e) { System.out.println("Clase no encontrada"); } catch (SQLException e ) { System.out.println(e); } } }
Actualizaciones.
600
import java.sql.*; public class Insertar { public static void main(String args[]) { String nombreCliente,ocupacion; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String bd = "jdbc:odbc:EjemploJava"; Connection conexion = DriverManager.getConnection(bd,"sa",null); nombreCliente = "Brozo"; ocupacion = "Payaso";
Inserción.
601
String sqlTexto = "INSERT INTO CLIENTE "
+"VALUES('"+nombreCliente+"','"+ocupacion+"')"; Statement sentenciaSQL = conexion.createStatement();
int renglonesAfectados = sentenciaSQL.executeUpdate(sqlTexto); if(renglonesAfectados==1) System.out.println("Datos agregados"); else System.out.println(“Error"); conexion.close(); sentenciaSQL.close(); } catch (ClassNotFoundException e) { System.out.println("Clase no encontrada"); } catch (SQLException e ) { System.out.println(e);} } }
Inserción.
603
import java.sql.*; public class Borrar { public static void main(String args[]) { String nombreCliente; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String bd = "jdbc:odbc:EjemploJava"; Connection conexion = DriverManager.getConnection(bd,"sa",null); nombreCliente = "x"; String sqlTexto = "DELETE FROM CLIENTE WHERE nombreCliente='" + nombreCliente+"'";
Borrado.
604
Statement sentenciaSQL = conexion.createStatement(); int renglonesAfectados = sentenciaSQL.executeUpdate(sqlTexto); if(renglonesAfectados==1) System.out.println("Datos eliminados"); else System.out.println("Error"); conexion.close(); sentenciaSQL.close(); } catch (ClassNotFoundException e) { System.out.println("Clase no encontrada"); } catch (SQLException e ) {System.out.println(e);} } }
Borrado.