PJ-020
FUNDAMENTOS DE JAVA
  www.profesorjava.com
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.
                   rauloramas@profesorjava.com
Java Language Basics


•   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
Anatomy of a Simple Java Program.



Comments




                                    main
                                    method


class “wrapper”
Anatomy of a Simple Java Program.
Anatomy of a Simple Java Program. Examples
Anatomy of a Simple Java Program. Examples
Built-In Data types. Example.
Built-In Data types. Example.
Built-In Data types.
Built-In Data types. Example.
Built-In Data types. Example.
Built-In Data types. Example.
Built-In Data types. Example.
++/-- Operators.


Java provides autoincrement(++) and autodecrement(--) operators;
++/-- Operators Example.
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.
Java Expressions. Example.




Expr
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
Casting
Casting
Casting




              1/2=0
          en 32 bits entero
Casting




          1.0 / 2 = 0 se representa en 64 bits
Casting
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 {…}
Block Structured Languages and the Scope of a Variable
Controlling a Program’s Execution Flow.




                                          do

       if




                           while
                                               for
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
Controlling a Program’s Execution Flow. If
Controlling a Program’s Execution Flow. If
Controlling a Program’s Execution Flow. If
Controlling a Program’s Execution Flow. If
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
Controlling a Program’s Execution Flow. Switch
Controlling a Program’s Execution Flow. Switch
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: while
Looping Statement Types: while
Looping Statement Types: while
Looping Statement Types: while
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
Looping Statement Types: for
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
for vs. while
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
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
Branching statements
Branching statements
Abstraction and Modeling
Abstraction and Modeling


•   Simplification Through Abstraction
•   Generalization Through Abstraction
•   Reuse of Abstractions
•   Inherent Challenges
•   Exercises




                                         57
Simplification Through Abstraction


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




                                                                 58
Simplification Through Abstraction




                                     59
Simplification Through Abstraction


One familiar example of an abstraction is a road map.




                                                        60
Simplification Through Abstraction


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.




                                                                 61
Simplification Through Abstraction


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.




                                                             62
Simplification Through Abstraction


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.




                                                             63
Simplification Through Abstraction


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.




                                                            64
Simplification Through Abstraction




                                     65
Generalization Through Abstraction


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:




                                                             66
Generalization Through Abstraction


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.




                                                              67
Organizing Abstractions Into Classification Hierarchies


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.




                                                             68
Organizing Abstractions Into Classification Hierarchies




                                                          69
Organizing Abstractions Into Classification Hierarchies




                                                          70
Organizing Abstractions Into Classification Hierarchies


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




                                                              71
Organizing Abstractions Into Classification Hierarchies


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




                                                             72
Organizing Abstractions Into Classification Hierarchies


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.




                                                              73
Organizing Abstractions Into Classification Hierarchies


A simple example of an abstraction hierarchy is shown below.


                                     Natural Objects



                 Plant                    Animal                    Mineral



 Mammal               Fish              Bird              Reptile         Insect




    Dog              Cat            Monkey


                                                                    74
Organizing Abstractions Into Classification Hierarchies


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:




                          Mammal




                            Dog               Cat         Monkey

                                                              75
Organizing Abstractions Into Classification Hierarchies


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.




                                         Mammal




                                            Dog           Cat        Monkey

                                                                76
Organizing Abstractions Into Classification Hierarchies


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




                                                             77
Organizing Abstractions Into Classification Hierarchies


Given these rules, neither an ostrich nor a penguin could be classified as a bird,
because neither can fly.


                    Birds                                 Non-Birds




                                                                  78
Organizing Abstractions Into Classification Hierarchies


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.




                                                              79
Organizing Abstractions Into Classification Hierarchies




                    Birds                                 Non-Birds




                                                                  80
Organizing Abstractions Into Classification Hierarchies


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




                                                              81
Organizing Abstractions Into Classification Hierarchies


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.




                                                              82
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.




                                                          83
Abstractions as the Basis for Software Development


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.




                                                              84
Abstractions as the Basis for Software Development


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.




                                                               85
Abstractions as the Basis for Software Development


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.




                                                           86
Abstractions as the Basis for Software Development



               A model is a simplification of the reality.




                                                     87
Abstractions as the Basis for Software Development


• 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.




                                                        88
Abstractions as the Basis for Software Development


The importance of modeling:

   Less Important                                              More Important




                Paper Airplane                       Fighter Jet




                                                          89
Abstractions as the Basis for Software Development


• 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




                                                          90
Abstractions as the Basis for Software Development


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.




                                                            91
Reuse of Abstractions


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.




                                                            92
Reuse of Abstractions


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.




                                                           93
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.


                                             94
Reuse of Abstractions


Pattern matching




                        95
Reuse of Abstractions




                        96
Reuse of Abstractions




                        97
Inherent Challenges


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.




                                                             98
Inherent Challenges




                      99
Objects and Classes
Objects and Classes


•   What is an object?
•   Methods
•   Reuse of Abstractions
•   Inherent Challenges
•   Exercises




                            101
What Is an Object?


 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




                                                          102
What Is an Object?




                     103
What Is an Object?


                              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




                                                         104
What Is an Object?


 A class is a general description of the properties and behaviours of some
  entities.

We described the class Waiter
giving the general description                                       Name of
                                                Waiter               class
of what properties Waiters have
                                                                     Properties
and what things Waiters can                    fullName
do.
                                              bringMenu
                                                                     Behaviours
                                              takeOrder
                                              bringMeal




                                                           105
What Is an Object?


 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




                                                             106
What Is an Object?




                     107
What Is an Object?


          Class      Object




                              108
What Is an Object?


Classes in Java may have methods and attributes.
    – Methods define actions that a class can perform.
    – Attributes describe the class.




                                                         109
What Is an Object?




                     110
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.




                                  111
What Is an Object?




                     112
What Is an Object?




                     113
What Is an Object?




                     114
What Is an Object?


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




                                                  115
BankAccount
What Is an Object?
                            accountName
                           accountNumber

                               credit
                               debit




                     116
What Is an Object?


Objects in Java are creating using the keyword new.




                                                      117
What Is an Object?


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.




                                                                Arguments




                                                          118
What Is an Object?




1. Declare a reference.
2. Create the object.
3. Assign values.




                          119
What Is an Object?




                     1. Declare a reference.
                     2. Create the object.




                     Two references to two
                     objects, with values
                     for their attributes.


                         120
What Is an Object?




                     121
What Is an Object?




                               size          ‘u0000’

                               price             0.0

                              lSleeved           false



AnotherShirt     0x334009                size            ‘u0000’

   myShirt       0x99f311                price             0.0

        id                               lSleeved         false
                  428802

               Stack memory              Heap memory

                                                            122
What Is an Object?




                               size          ‘u0000’

                               price             0.0

                              lSleeved           false



AnotherShirt       X
                 0x334009
                              X          size            ‘u0000’
                 0x99f311                price             0.0

   myShirt       0x99f311                lSleeved         false


               Stack memory              Heap memory

                                                            123
What Is an Object. Examples.


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);
  }
}


                                             124
What Is an Object. Examples.


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);
  }
}                                                          125
What Is an Object. Examples.


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);
  }
}




                                                 126
What Is an Object. Examples.


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);
  }
}


                                                       127
Objects Interactions
Objects Interactions


• Methods
• Exercises




                       129
Methods


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)




                                                            130
Methods


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:




                                                             131
Methods


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:




                                                           132
Methods


The message may require some parameters (i.e., pieces of data):




                                                          133
Methods


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:




                                                            134
Methods


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:




                                                             135
Methods




          136
Methods


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.
                                                             137
Methods


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.




                                                            138
Methods




          139
Methods


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.




                                                         140
Methods


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




                                                             141
Methods




          142
Methods




          143
Methods




          144
Methods




          145
Methods




          Calling its method




                               146
Methods


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.




                                                            147
Methods




          148
Methods




          149
Methods




          150
Collection of Objects
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.




                                                             152
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




                                                           153
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:




                                                       154
The Vector Class.




                    155
The Vector Class.




                    156
The Vector Class.




                    157
The Vector Class.




                    158
The Vector Class.




                    159
The Vector Class.




                    160
The Vector Class.




                    161
The Vector Class.




                    162
The Vector Class.




                    163
The Vector Class.




                    164
HashTable.


• Maps keys to values
• Keys and values can be any non-null object




                                               165
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()




                                                               166
Enumeration Interface.




                         167
The Collection API.




                      168
The Collection API.




                      169
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.




                                                            170
HashSet Class.




                 171
TreeSet Class.




                 172
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()




                                                             173
Iterator Interface.




                      174
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.




                                                                 175
List Interface.




                  176
ListIterator Interface.




                          177
LinkedList Class.




                    178
LinkedList Class.




                    179
Concrete Collections.




                        180
Objects 1
1. Objects
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)


                                                           183
Overview of Object Orientation.




                                  184
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.


                                                        185
Identifying Objects.




  An object is an entity with a well-defined boundary and
  identity that encapsulates state and behavior.


                                               186
Identifying Objects.




                       187
Identifying Objects.


Physical entity



Conceptual entity
(Chemical process)



Software entity
(Linked list)




                       188
Identifying Objects.


• Objects have many forms:
   – Tangible things (Airplane, Computer, Car)
   – Roles (Doctor, Teacher)
   – Incidents (Meeting)
   – Interactions (Interview, Agreement)




                                                 189
Object definition. Case Study


• Throughout this course, a case study of a clothing catalog, DirectClothing,
  Inc., will be used to illustrate concepts.




                                                            190
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.




                                                          191
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



                                                            192
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




                                                           193
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




                                             194
Object definition. Case Study


   inventory
   back-ordered items
   system
   Internet
   business
   year
   month
   order form
   check




                                195
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

                                                     196
Identifying Object Attributes and Operations




                                               197
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.




                                                            198
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?




                                                           199
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




                                                        200
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?




                                                               201
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?




                                                            202
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




                                                            203
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.




                                                            204
Independent Existence.


• To be an object and not a characteristic of another object, the object must
  need to exist independently




                                                           205
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.




                                                            206
Attributes and Operations.


• An object must have attributes and operations
• If it does not, it is probably and attribute or operation of another object




                                                              207
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.




                                                           208
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




                                                           209
Encapsulation.




                 210
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




                                                           211
Objects 2
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)


                                                           213
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.




                                                              214
Class Overview.


• An object is an instance of a class.




                                         215
Class Overview.


A class is represented using a rectangle with compartments.




                                                              216
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.




                                                              217
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.




                                                            218
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.




                                                          219
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.




                                                                 220
Generalization


A relationship among classes where one class shares the
structure and/or behavior of one or more classes.




                                                          221
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.




                                                             222
Inheritance




              223
Inheritance




              224
Inheritance




              225
Inheritance




              226
Specialization


Specialization is inheritance with the addition and modification
of methods to solve a specific problem.




                                                             227
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




                                                           228
Polymorphism


Polymorphism is the ability to hide many different
implementations behind a single interface.




                                                     229
Polymorphism


Interfaces formalize polymorphism.




                                     230
Objects 3
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.




                                                           232
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)




                                                           233
Association and Composition.


• a




                               234
Association and Composition.


• a




                               235
Association and Composition.


• a




                               236
Association and Composition.


• a




                               237
Association and Composition.


• a




                               238
Association and Composition.


• a




                               239
Association and Composition.


• a




                               240
Association and Composition.


• a




                               241
Association and Composition.


• a




                               242
Association and Composition.


• a




                               243
Association and Composition.


• a




                               244
Association and Composition.


• a




                               245
Association and Composition.


• a




                               246
Objects 4
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




                                                          248
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.”




                                                             249
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.




                                                             250
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.




                                                              251
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.




                                                            252
Use Case Diagrams.




                     253
Use Case Diagrams.




                     254
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.




                                                             255
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."




                                          256
Example: Use Case Diagrams.


Restocking a soda machine is an important use case.




                                                      257
Example: Use Case Diagrams.


Collecting the money
from a soda machine
is another
important use case.




                              258
Example: Use Case Diagrams.




                              259
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.




                                                          260
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. "




                                                           261
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).




                                                            262
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.




                                                          263
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.




                                                               264
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.




                                                                 265
Use Case Diagrams.




                     266
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.




                                                             267
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).




                                                          268
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.




                                                         269
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.




                                                         270
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.




                                                            271
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




                                                                272
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.




                                                           273
Example: Use Case Diagrams.


Actores que interactuan con el sistema:




                                          274
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.




                                                             275
Example: Use Case Diagrams.


Un item puede ser una Botella, un Tarro o una Jaba.




                                                      276
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.




                                                              277
Example: Use Case Diagrams.




                              278
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).




                                                             279
Example: Use Case Diagrams.




                              280
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).




                                                             281
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.




                                                         282
Exercises: Use Case Diagrams.


Encontrar los casos de uso para las tareas uno y dos.




                                                        283
Use Case Diagrams.




                     284
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.




                                                           285
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




                                                            286
Sequence Diagrams.




                     287
Sequence Diagrams.



                                                         :Sistema
                 :cajero
                               crearNuevaVenta()

                           ingresarItem(codItem, cant)


                                  descripción, total
    Bucle
                                   *[más items]

                                 finalizarVenta()

                                  total con imptos.

                                 realizarPago()

                                monto cambio, recibo




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.

                                                                288
Sequence Diagrams.




                :JuegodeDados                    dado1:Dados   dado2:Dados


              jugar()
                                 lanzar()


                         val1:=getValorMostrado()


                                            lanzar()


                                 val2:=getValorMostrado()




                                                                    289
Sequence Diagrams.



                :Computer                 :PrintServer             :Printer

         print(arch)
                            print(arch)             [no queue]
                                                    print(arch)




                                                                  290
Sequence Diagrams.

                        Objetos participantes en la interacción


                  :Computer                 :PrintServer             :Printer

        print(arch)           print(arch)             [no queue]            Condición
                                                      print(arch)
     Mensaje
                           Mensaje
                          Sincrónico
    Activación




       Línea de
         vida                 Retorno
                       Puede omitirse

                                                                    291
Sequence Diagrams.

                                       Flecha hacia un objeto
                      :ItemWindow    índica creación del objeto.
 NuevoItem(data)
                              crearItem(data)
                                                      :Item




                      :ItemWindow                     :Item
     EliminarItem()


                               BorrarItem()
                                                       X

                                          X indica destrucción del objeto

                                                        292
Sequence Diagrams.


                     Mensaje Simple / Sincrónico
                     No se dan detalles de la comunicación cuando no
                     son conocidos o no son relevantes.

                     Respuesta / Resultado

                        Mensaje Asincrónico


Sintaxis del mensaje:
Número de secuencia [condición] * [expresión iteración]
     valor de retorno := nombre del mensaje (parámetros)


                                                    293
Sequence Diagrams.


               a1:ClaseA       b1:ClaseB


                       [x<0] Op1()
                                           :ClaseC
                       [x>0] Op1()



                                             X

    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.

                                                     294
Sequence Diagrams.




                 a1:Order                       b1:OrderLine
  OrderTotal()
                            *[for each] subtotal()




    Sintaxis: * [expresión-iteación ] mensaje



                                                         295
Sequence Diagrams.




                     296
Sequence Diagrams.




                     Activation boxes represent the
                     time an object needs to
                     complete a task




                                    297
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.




                                          298
Sequence Diagrams.


                     Lifelines are vertical dashed
                     lines that indicate the object's
                     presence over time.




                                     299
Sequence Diagrams.


                     Objects can be terminated
                     early using an arrow labeled
                     "< < destroy > >" that points to
                     an X.




                                     300
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 [ ].




                                     301
Example:




           302
Example:




           303
Example:




           304
Example:




           305
Example:




           306
Example:




           307
Example:




           308
Example:




           309
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.




                                                               310
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.




                                                           311
Sequence Diagrams.


GENERAR EL DIAGRAMA DE SECUENCIA PARA LA
MAQUINA RECICLADORA.




                                           312
Collaboration Diagrams.




                          313
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




                                                          314
Sequence Diagrams.




                     315
Sequence Diagrams.




                     316
Sequence Diagrams.




                     317
Arrays
Declaring arrays.


• 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.




                                                319
Declaring arrays.


• 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;
}




                                                   320
Initializing Arrays.


• 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) };

                                                                 321
Multidimensional Arrays.


• Arrays of arrays:

int twoDim [][] = new int [4][];
twoDim[0] = new int[5];
twoDim[1] = new int[5];
int twoDim [][] = new int [][4]; illegal




                                           322
Multidimensional Arrays.




                           323
Multidimensional Arrays.




                           324
Multidimensional Arrays.


• 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];




                                                325
Array Bounds.


• All array subscripts begin at 0:

int list[] = new int [10];
for (int i = 0; i < list.length; i++) {
  System.out.println(list[i]);
}




                                          326
Array Resizing.


• 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];




                                                           327
Copying arrays


The System.arraycopy() method:




                                 328
Copying arrays


The System.arraycopy() method:




                                 329
Class Design
Subclassing




              331
Subclassing




              332
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>*
   }




                                                            333
Single Inheritance




                     334
Access Control




                 335
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




                                                           336
Overriding Methods




                     337
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.




                                                           338
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.




                                                           339
Virtual Method Invocation


• Virtual method invocation:
        Employee e = new Manager();
        e.getDetails();
• Compile-time type and runtime type




                                       340
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




                                                       341
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();



                                                            342
The InstanceOf Operator




                          343
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.




                                                             344
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.




                                     345
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.




                                                              346
Overloading Constructors




                           347
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 {
        ...
        }




                                                            348
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.




                                                           349
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.




                                                            350
Wrapper Classes




                  351
Advanced Class Features
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.”




                                                           353
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)




                                                            354
Class Attributes


• You can invoke static method without any instance of the class to which it
  belongs.




                                                           355
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.




                                                            356
Abstract Classes


• An abstract class models a class of objects where the full implementation is
  not known but is supplied by the concrete subclasses.




                                                            357
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>*
}




                                                            358
Interfaces




             359
Java Language Basics




                       360
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



                                        361
Review.

Classes in Java may have methods and attributes.
  – Methods define actions that a class can perform.
  – Attributes describe the class.




                                           362
Review.




          363
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.




                                  364
Review.




          365
Review.




          366
Review.

• Inheritance - a Fish is Also a Pet




                                       367
Review.




          368
Review.




          369
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.




                                             370
Inheritance.




               371
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.




                                             372
Inheritance Hierarchy.




                         373
Inheritance Hierarchy.




                         374
Inheritance Hierarchy.




                         375
Inheritance Hierarchy.




                         376
Inheritance Hierarchy.




                   Animal


            Cat      Dog    Horse




                                    377
Inheritance Hierarchy.




                         378
The Constructor Process.




                           379
Inheritance Hierarchy.




                         380
Inheritance Hierarchy.




                         381
Overriding.




              382
Polymorphism.




                383
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.

                                             384
Dynamic Binding and Polymorphism.




                                    385
Dynamic Binding and Polymorphism.




                              386
Dynamic Binding and Polymorphism.




                              387
Dynamic Binding and Polymorphism.




                              388
Upcast/Downcast.




                   389
Abstract Classes.




                    390
Abstract Classes.




                    391
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).




                                               392
Interfaces.




              393
Interfaces.




              394
Interfaces.




              395
Exceptions and Exceptions Handling
Exceptions.


• 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




                                                           397
Exceptions.


• 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



                                                          398
The Exceptions Hierarchy


• 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




                                                            399
The Exceptions Hierarchy




                           400
Handling Exceptions


• Checked exceptions must be either handled in the method where they are
  generated, or delegated to the calling method




                                                        401
Keywords


• 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)

                                                           402
try/catch blocks


• 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




                                                            403
The catch clause


• 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




                                                          404
Example




          405
Example




          406
The finally clause


• 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




                                                          407
Example




          408
Nested Exception Handling


• 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




                                                            409
The throw keyword


•   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




                                                            410
Handling runtime exceptions


• 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




                                                          411
Assertions


• 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




                                                           412
Using assertions


• 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




                                                          413
When to use assertions


• 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




                                                           414
When to use assertions


• 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




                                                           415
Building Java Guis
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




                                                           417
Abstract Window Toolkit (AWT).




                                 418
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.




                                                             419
Containers.




              420
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.




                                                            421
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.



                                                              422
Frames.




          423
Frames.




          424
Frames.




          425
Frames.




          426
Frames.




          427
Frames.




          428
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.




                                                                429
The Panel Class.




                   430
The Panel Class.




                   431
Containers Layouts.


•   FlowLayout
•   BorderLayout
•   GridLayout
•   CardLayout
•   GridBagLayout




                      432
Default Layout Managers.




                           433
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




                                      434
The FlowLayout Manager.




                          435
The FlowLayout Manager.




                          436
The FlowLayout Manager.




                          437
The BorderLayout Manager.


Default layout for the Frame class

Components added to specific regions.




                                        438
The BorderLayout Manager.




                            439
The BorderLayout Manager.




                            440
The BorderLayout Manager.




                            441
The BorderLayout Manager.




                            442
The GridLayout Manager.


• Components are added left to right, top to bottom.
• All regions are equally sized.
• The constructor specifies the rows and columns.




                                                       443
The GridLayout Manager.




                          444
The GridLayout Manager.




                          445
The GridLayout Manager.




                          446
The GridLayout Manager.




                          447
Gui Event Handling
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




                                                          449
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.




                                                          450
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.




                                                           451
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.




                                                            452
GUI Based Applications
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.




                                                            454
How to create a menu.




                        455
How to create a menu.




                        456
How to create a menu.




                        457
How to create a menu.




                        458
Threads
Processes and Threads.


• 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




                                                           460
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




                                                           461
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




                                                           462
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()
...



                                                             463
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();
...




                                                             464
Example: subclassing the Thread class.




                                         465
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




                                                           466
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




                                                          467
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;
    .........
}
                                                             468
Stopping Threads.




                    469
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




                                                          470
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




                                                           471
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




                                                         472
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




                                                            473
Multi-Threading: need for synchronization




                                            474
Multi-Threading: need for synchronization




                                            475
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()




                                                          476
Advanced I/O Streams
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.




                                                             478
What Is a Stream?.




                     479
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.




                                                             480
What Is a Stream?.




                     481
What Is a Stream?.




                     482
What Is a Stream?.




                     483
What Is a Stream?.




                     484
What Is a Stream?.




                     485
InputStream, OutputStream, Reader and Writer.




                                                486
Converting a Byte Stream into a Character Stream.




                                                    487
Wrapper Streams.


Wrapping streams allows you to create more efficient
programs.




                                                       488
Wrapper Example.




                   489
I/O Objects in Java.




                       490
Console Example.




                   491
File I/O.


Using FileReader and FileWriter you can read from and write
to files.




                                                              492
File I/O Example.




                    493
Databases in Java
Microsoft® SQL Server™ es una base de datos
relacional cliente-servidor basada en el Lenguaje
de consulta estructurado (SQL, Structured Query
Language).




                                     495
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.

                                      496
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.

                                        497
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).


                                    498
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.
                                        499
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).


                                      500
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.



                                        501
Base de datos relacional (Tablas).

Las tablas están compuestas de columnas y filas
(atributos y tuplas en la teoría relacional).
                             Columna
   Tupla, fila

        id       nombre   Descripción   tamaño         Atributos

       300       Camisa   Cuello V      Ch

       301       Camisa   Ovalada       M

       302       Camisa   Manga Corta   S

                                                 502
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.


                                        503
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.
                                      504
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.

                                       505
Aplicaciones Cliente                Cliente-servidor.

                        SQL Server
Administrador

                                               Base
                                                de
   Usuario                                     Datos



   Usuario
                                         506
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.



                                        507
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).



                                       508
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).
                                       509
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.



                                        510
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.




                                       511
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.




                                      512
513
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




                                               514
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.



                                       515
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.

                                        516
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.



                                       517
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.




                                          518
Una Tabla debe Tener un Identificador




 PK Llave primaria
                                    519
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.



                                        520
Columna
   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        Columna
Identity     Not Null         Null


                                           521
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.




                                        522
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.




                                         523
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.




                                     524
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.




                                         525
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.




                                       526
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.




                                      527
528
Definición de objetos de una base de datos.

CREATE object_name.

ALTER object_name.

DROP object_name.




                                    529
LMD se usa para recuperar datos de la base de
datos.

SELECT

INSERT

UPDATE

DELETE


                                   530
Para crear una tabla.

Create Table <Table_Name>
(
  Column_Name tipoDeDato (identity | Null | Not
  Null),
  [...más columnas separadas por comas...]
)




                                      531
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   Tipo de    Null o
Columna     Dato       Not Null
                                    532
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]



                                    533
Agregando y eliminando columnas.

ELIMINAR COLUMNAS

ALTER TABLE tabla
DROP nombre_columna <tipo> [NULL | NOT NULL]




                                   534
Agregando y eliminando columnas.

          ALTER TABLE empleado
          ADD rfc char(10) null

  empID      nombre   apPaterno   apMaterno     rfc




            ALTER TABLE empleado
            DROP COLUMN apMaterno
                                          535
Borrado de una tabla.

DROP TABLE tabla

Ejemplo:

DROP TABLE empleado




                        536
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’)


                                     537
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.


                                     538
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
                                      539
RECUPERAR DATOS.

SELECT nombre
FROM empleado

SELECT nombre,apPaterno,apMaterno
FROM empleado

SELECT nombre,apPaterno
FROM empleado
WHERE nombre=‘Juan’

                                    540
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.



                                       541
ACTUALIZAR DATOS.

UPDATE empleado
SET apMaterno=‘el mismo para todos’

UPDATE empleado
SET nombre=‘Raul’
WHERE nombre=‘Juan’




                                      542
ELIMINANDO DATOS.

La instrucción DELETE se usa para eliminar datos
de una tabla.

EJEMPLO:

DELETE FROM empleado
WHERE nombre=‘Raul’



                                     543
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:


                                        544
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

                                    545
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.

                                        546
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.


                                       547
RESTRICCIONES DE CLAVE PRINCIPAL.

CREATE TABLE Autores   Tabla sin llave primaria
(
  AutorID not null,
  Nombre not null,
  Apellido not null,
  AñoNac null,
  AñoMuerte null,
  Descripcion null
)

                                  548
RESTRICCIONES DE CLAVE PRINCIPAL.

CREATE TABLE Autores       Tabla con llave primaria
(
  AutorID not null,
  Nombre not null,
  Apellido not null,
  AñoNac null,
  AñoMuerte null,
  Descripcion null,
  CONSTRAINT autor_pk PRIMARY KEY(AutorID)
)

          Nombre de la llave primaria
                                        549
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.
                                         550
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)
)

                                    551
RESTRICCIONES DE CLAVE EXTERNA.

CREATE TABLE Libros (               Tabla sin FK
  LibroID char(8) not null,
  Titulo varchar(60) not null,
  Editor varchar(60) null,
  FechaEd date null,
  Costo float not null,        CondicionID no tiene ninguna
  CondicionID int not null, celación con el otro nombre de
  Vendido char(2) null         Columna de la tabla
)                              LibroEstado



                                              552
RESTRICCIONES DE CLAVE EXTERNA.

CREATE TABLE Libros (          Tabla con FK
  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)              DE LA TABLA
)                                       LIBROESTADO
                                          553
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:
                                       554
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.




                                      555
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),
)


                                    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 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.


                                      558
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.




                                      559
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), Restricción check
  CondicionID int not null,
  Vendido char(2) null,
  CONSTRAINT libro_pk PRIMARY KEY(CondicionID),
  FOREIGN KEY(CondicionID) REFERENCES
  LibroEstado(CondicionID)
)
                                       560
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.

                                      561
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.
                                        562
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),
)
                                     563
Databases in Java
Diseño de una aplicación Java
 con acceso a Base de Datos.




                      565
Bases de Datos Relacionales.

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).




                                       566
Bases de Datos Relacionales.

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)
)



                                          567
Bases de Datos Relacionales.

3. Configurar el DSN del usuario y del sistema con el
   nombre lógico EjemploJava.




                                         568
Bases de Datos Relacionales.

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.
                                          569
Bases de Datos Relacionales.

CONSULTAR DATOS.

SELECT * FROM CLIENTE

SELECT nombreCliente, ocupacion FROM CLIENTE

SELECT nombreCliente FROM CLIENTE

SELECT nombreCliente FROM CLIENTE
WHERE ocupacion=“profesor”


                                  570
Bases de Datos Relacionales.

BORRAR DATOS.

DELETE FROM Cliente
Where ocupacion=“estudiante”

DELETE FROM Cliente




                                   571
Bases de Datos Relacionales.

MODIFICAR DATOS.

UPDATE Cliente
SET ocupacion=“estudiante”
WHERE ocupacion=“actor”

UPDATE Cliente
SET ocupacion=“actor”
WHERE nombreCliente=“Juan Perez”



                                   572
Arquitectura de la aplicación.




                       573
Arquitectura de la aplicación.

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).


                                         574
Arquitectura de la aplicación.

.




                               575
Arquitectura de la aplicación.

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.
                                       576
Arquitectura de la aplicación.

El siguiente gráfico muestra la arquitectura del sistema
de vista desde el nivel de aplicación, usando Java.




                                         577
Arquitectura de la aplicación.

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.
                                          578
Arquitectura de la aplicación.

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.




                                       579
Arquitectura de la aplicación.

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.




                                        580
Conexión a una base de datos.




                      581
Conexión a una base de datos.

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.
                                       582
Conexión a una base de datos.

Las clases e interfaces que utilizaremos se encuentran en el
paquete java.sql

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:




                                                 583
Conexión a una base de datos.

Primero establecemos el driver a utilizar (ODBC) que nos
proporciona la biblioteca JDBC.

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:




                                                 584
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.
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:



                                                 585
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.

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:




                                                 586
Conexión a una base de datos.
Utilizando el método createStatement, perteneciente al objeto de
tipo Connection, creamos el objeto de tipo Statement.
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: }
                                               587
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.
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: }
                                               588
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.
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: }
                                               589
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.

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: }
                                               590
25:}
Consultas y ResultSet.




                   591
Consultas y ResultSet.

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.




                                        592
Consultas y ResultSet.

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();




                                             593
Consultas y ResultSet.

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("**********");
}




                                             594
Consultas y ResultSet.

   cliente.close();
   conexion.close();
   sentenciaSQL.close();
  }
  catch (ClassNotFoundException e) {
   System.out.println("Clase no encontrada");
  }
  catch (SQLException e ) {
   System.out.println(e);
  }
 }
}




                                                595
Actualizaciones.




                   596
Actualizaciones.

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);
                                                       597
Actualizaciones.

        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);
          }
    }
}
                                                    598
Inserción.




             599
Inserción.

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";




                                              600
Inserción.
    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);}
    }
}                                                  601
Borrado.




           602
Borrado.

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+"'";



                                             603
Borrado.

        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);}
    }
}
                                                   604

More Related Content

PDF
03 expressions.ppt
DOCX
C programming structures &amp; union
PDF
Structured Query Language
PDF
Research Inventy : International Journal of Engineering and Science is publis...
PDF
Pj100 modulo 01
PDF
Programación para niños app inventor
PDF
Curso de Programación Java Intermedio
PDF
Praktiketako aurkezpena
03 expressions.ppt
C programming structures &amp; union
Structured Query Language
Research Inventy : International Journal of Engineering and Science is publis...
Pj100 modulo 01
Programación para niños app inventor
Curso de Programación Java Intermedio
Praktiketako aurkezpena

Similar to P J020 (20)

PPT
73d32 session1 c++
PPTX
Introduction to C ++.pptx
PPTX
What To Leave Implicit
PPT
principles of object oriented class design
PDF
Subprogram
PDF
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
PPT
Csharp
PPTX
ANALYSIS AND DESIGN OF ALGORITHMS -M1-PPT
PPT
Oop(object oriented programming)
PPTX
Java script
PPTX
Pi j3.2 polymorphism
PPT
core_java.ppt
PDF
Bound and Checked
PPT
Java introduction
PPTX
OOP-JAVA-ONLYUNIT-2-PPT_removed (1).pptx
PDF
Lecture1
PPTX
C# 101: Intro to Programming with C#
PPTX
C language (Part 2)
PDF
New c sharp3_features_(linq)_part_ii
PDF
Predictable reactive state management - ngrx
73d32 session1 c++
Introduction to C ++.pptx
What To Leave Implicit
principles of object oriented class design
Subprogram
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Csharp
ANALYSIS AND DESIGN OF ALGORITHMS -M1-PPT
Oop(object oriented programming)
Java script
Pi j3.2 polymorphism
core_java.ppt
Bound and Checked
Java introduction
OOP-JAVA-ONLYUNIT-2-PPT_removed (1).pptx
Lecture1
C# 101: Intro to Programming with C#
C language (Part 2)
New c sharp3_features_(linq)_part_ii
Predictable reactive state management - ngrx
Ad

P J020

  • 1. PJ-020 FUNDAMENTOS DE JAVA www.profesorjava.com
  • 2. 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.
  • 3. 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. rauloramas@profesorjava.com
  • 4. Java Language Basics • 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
  • 5. Anatomy of a Simple Java Program. Comments main method class “wrapper”
  • 6. Anatomy of a Simple Java Program.
  • 7. Anatomy of a Simple Java Program. Examples
  • 8. Anatomy of a Simple Java Program. Examples
  • 16. ++/-- Operators. Java provides autoincrement(++) and autodecrement(--) operators;
  • 18. 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.
  • 20. 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.
  • 21. 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
  • 22. 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
  • 23. 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
  • 26. Casting 1/2=0 en 32 bits entero
  • 27. Casting 1.0 / 2 = 0 se representa en 64 bits
  • 29. 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 {…}
  • 30. Block Structured Languages and the Scope of a Variable
  • 31. Controlling a Program’s Execution Flow. do if while for
  • 32. 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
  • 33. Controlling a Program’s Execution Flow. If
  • 34. Controlling a Program’s Execution Flow. If
  • 35. Controlling a Program’s Execution Flow. If
  • 36. Controlling a Program’s Execution Flow. If
  • 37. Controlling a Program’s Execution Flow. If
  • 38. 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
  • 39. 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
  • 40. Controlling a Program’s Execution Flow. Switch
  • 41. Controlling a Program’s Execution Flow. Switch
  • 42. 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.
  • 47. 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
  • 49. 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
  • 51. 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
  • 53. 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. Abstraction and Modeling • Simplification Through Abstraction • Generalization Through Abstraction • Reuse of Abstractions • Inherent Challenges • Exercises 57
  • 58. Simplification Through Abstraction 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 58
  • 60. Simplification Through Abstraction One familiar example of an abstraction is a road map. 60
  • 61. Simplification Through Abstraction 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. 61
  • 62. Simplification Through Abstraction 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. 62
  • 63. Simplification Through Abstraction 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. 63
  • 64. Simplification Through Abstraction 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. 64
  • 66. Generalization Through Abstraction 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: 66
  • 67. Generalization Through Abstraction 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. 67
  • 68. Organizing Abstractions Into Classification Hierarchies 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. 68
  • 69. Organizing Abstractions Into Classification Hierarchies 69
  • 70. Organizing Abstractions Into Classification Hierarchies 70
  • 71. Organizing Abstractions Into Classification Hierarchies 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 71
  • 72. Organizing Abstractions Into Classification Hierarchies 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 72
  • 73. Organizing Abstractions Into Classification Hierarchies 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. 73
  • 74. Organizing Abstractions Into Classification Hierarchies A simple example of an abstraction hierarchy is shown below. Natural Objects Plant Animal Mineral Mammal Fish Bird Reptile Insect Dog Cat Monkey 74
  • 75. Organizing Abstractions Into Classification Hierarchies 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: Mammal Dog Cat Monkey 75
  • 76. Organizing Abstractions Into Classification Hierarchies 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. Mammal Dog Cat Monkey 76
  • 77. Organizing Abstractions Into Classification Hierarchies 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 77
  • 78. Organizing Abstractions Into Classification Hierarchies Given these rules, neither an ostrich nor a penguin could be classified as a bird, because neither can fly. Birds Non-Birds 78
  • 79. Organizing Abstractions Into Classification Hierarchies 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. 79
  • 80. Organizing Abstractions Into Classification Hierarchies Birds Non-Birds 80
  • 81. Organizing Abstractions Into Classification Hierarchies 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 81
  • 82. Organizing Abstractions Into Classification Hierarchies 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. 82
  • 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. 83
  • 84. Abstractions as the Basis for Software Development 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. 84
  • 85. Abstractions as the Basis for Software Development 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. 85
  • 86. Abstractions as the Basis for Software Development 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. 86
  • 87. Abstractions as the Basis for Software Development A model is a simplification of the reality. 87
  • 88. Abstractions as the Basis for Software Development • 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. 88
  • 89. Abstractions as the Basis for Software Development The importance of modeling: Less Important More Important Paper Airplane Fighter Jet 89
  • 90. Abstractions as the Basis for Software Development • 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 90
  • 91. Abstractions as the Basis for Software Development 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. 91
  • 92. Reuse of Abstractions 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. 92
  • 93. Reuse of Abstractions 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. 93
  • 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. 94
  • 98. Inherent Challenges 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. 98
  • 101. Objects and Classes • What is an object? • Methods • Reuse of Abstractions • Inherent Challenges • Exercises 101
  • 102. What Is an Object?  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 102
  • 103. What Is an Object? 103
  • 104. What Is an Object? 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 104
  • 105. What Is an Object?  A class is a general description of the properties and behaviours of some entities. We described the class Waiter giving the general description Name of Waiter class of what properties Waiters have Properties and what things Waiters can fullName do. bringMenu Behaviours takeOrder bringMeal 105
  • 106. What Is an Object?  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 106
  • 107. What Is an Object? 107
  • 108. What Is an Object? Class Object 108
  • 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. 109
  • 110. What Is an Object? 110
  • 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. 111
  • 112. What Is an Object? 112
  • 113. What Is an Object? 113
  • 114. What Is an Object? 114
  • 115. What Is an Object? 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 115
  • 116. BankAccount What Is an Object? accountName accountNumber credit debit 116
  • 117. What Is an Object? Objects in Java are creating using the keyword new. 117
  • 118. What Is an Object? 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. Arguments 118
  • 119. What Is an Object? 1. Declare a reference. 2. Create the object. 3. Assign values. 119
  • 120. What Is an Object? 1. Declare a reference. 2. Create the object. Two references to two objects, with values for their attributes. 120
  • 121. What Is an Object? 121
  • 122. What Is an Object? size ‘u0000’ price 0.0 lSleeved false AnotherShirt 0x334009 size ‘u0000’ myShirt 0x99f311 price 0.0 id lSleeved false 428802 Stack memory Heap memory 122
  • 123. What Is an Object? size ‘u0000’ price 0.0 lSleeved false AnotherShirt X 0x334009 X size ‘u0000’ 0x99f311 price 0.0 myShirt 0x99f311 lSleeved false Stack memory Heap memory 123
  • 124. What Is an Object. Examples. 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); } } 124
  • 125. What Is an Object. Examples. 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); } } 125
  • 126. What Is an Object. Examples. 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); } } 126
  • 127. What Is an Object. Examples. 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); } } 127
  • 130. Methods 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) 130
  • 131. Methods 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: 131
  • 132. Methods 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: 132
  • 133. Methods The message may require some parameters (i.e., pieces of data): 133
  • 134. Methods 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: 134
  • 135. Methods 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: 135
  • 136. Methods 136
  • 137. Methods 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. 137
  • 138. Methods 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. 138
  • 139. Methods 139
  • 140. Methods 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. 140
  • 141. Methods 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 141
  • 142. Methods 142
  • 143. Methods 143
  • 144. Methods 144
  • 145. Methods 145
  • 146. Methods Calling its method 146
  • 147. Methods 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. 147
  • 148. Methods 148
  • 149. Methods 149
  • 150. Methods 150
  • 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. 152
  • 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 153
  • 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: 154
  • 165. HashTable. • Maps keys to values • Keys and values can be any non-null object 165
  • 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() 166
  • 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. 170
  • 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() 173
  • 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. 175
  • 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) 183
  • 184. Overview of Object Orientation. 184
  • 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. 185
  • 186. Identifying Objects. An object is an entity with a well-defined boundary and identity that encapsulates state and behavior. 186
  • 188. Identifying Objects. Physical entity Conceptual entity (Chemical process) Software entity (Linked list) 188
  • 189. Identifying Objects. • Objects have many forms: – Tangible things (Airplane, Computer, Car) – Roles (Doctor, Teacher) – Incidents (Meeting) – Interactions (Interview, Agreement) 189
  • 190. Object definition. Case Study • Throughout this course, a case study of a clothing catalog, DirectClothing, Inc., will be used to illustrate concepts. 190
  • 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. 191
  • 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 192
  • 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 193
  • 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 194
  • 195. Object definition. Case Study  inventory  back-ordered items  system  Internet  business  year  month  order form  check 195
  • 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 196
  • 197. Identifying Object Attributes and Operations 197
  • 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. 198
  • 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? 199
  • 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 200
  • 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? 201
  • 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? 202
  • 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 203
  • 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. 204
  • 205. Independent Existence. • To be an object and not a characteristic of another object, the object must need to exist independently 205
  • 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. 206
  • 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 207
  • 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. 208
  • 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 209
  • 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 211
  • 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) 213
  • 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. 214
  • 215. Class Overview. • An object is an instance of a class. 215
  • 216. Class Overview. A class is represented using a rectangle with compartments. 216
  • 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. 217
  • 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. 218
  • 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. 219
  • 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. 220
  • 221. Generalization A relationship among classes where one class shares the structure and/or behavior of one or more classes. 221
  • 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. 222
  • 223. Inheritance 223
  • 224. Inheritance 224
  • 225. Inheritance 225
  • 226. Inheritance 226
  • 227. Specialization Specialization is inheritance with the addition and modification of methods to solve a specific problem. 227
  • 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 228
  • 229. Polymorphism Polymorphism is the ability to hide many different implementations behind a single interface. 229
  • 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. 232
  • 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) 233
  • 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 248
  • 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.” 249
  • 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. 250
  • 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. 251
  • 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. 252
  • 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. 255
  • 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." 256
  • 257. Example: Use Case Diagrams. Restocking a soda machine is an important use case. 257
  • 258. Example: Use Case Diagrams. Collecting the money from a soda machine is another important use case. 258
  • 259. Example: Use Case Diagrams. 259
  • 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. 260
  • 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. " 261
  • 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). 262
  • 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. 263
  • 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. 264
  • 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. 265
  • 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. 267
  • 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). 268
  • 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. 269
  • 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. 270
  • 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. 271
  • 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 272
  • 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. 273
  • 274. Example: Use Case Diagrams. Actores que interactuan con el sistema: 274
  • 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. 275
  • 276. Example: Use Case Diagrams. Un item puede ser una Botella, un Tarro o una Jaba. 276
  • 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. 277
  • 278. Example: Use Case Diagrams. 278
  • 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). 279
  • 280. Example: Use Case Diagrams. 280
  • 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). 281
  • 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. 282
  • 283. Exercises: Use Case Diagrams. Encontrar los casos de uso para las tareas uno y dos. 283
  • 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. 285
  • 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 286
  • 288. Sequence Diagrams. :Sistema :cajero crearNuevaVenta() ingresarItem(codItem, cant) descripción, total Bucle *[más items] finalizarVenta() total con imptos. realizarPago() monto cambio, recibo 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. 288
  • 289. Sequence Diagrams. :JuegodeDados dado1:Dados dado2:Dados jugar() lanzar() val1:=getValorMostrado() lanzar() val2:=getValorMostrado() 289
  • 290. Sequence Diagrams. :Computer :PrintServer :Printer print(arch) print(arch) [no queue] print(arch) 290
  • 291. Sequence Diagrams. Objetos participantes en la interacción :Computer :PrintServer :Printer print(arch) print(arch) [no queue] Condición print(arch) Mensaje Mensaje Sincrónico Activación Línea de vida Retorno Puede omitirse 291
  • 292. Sequence Diagrams. Flecha hacia un objeto :ItemWindow índica creación del objeto. NuevoItem(data) crearItem(data) :Item :ItemWindow :Item EliminarItem() BorrarItem() X X indica destrucción del objeto 292
  • 293. Sequence Diagrams. Mensaje Simple / Sincrónico No se dan detalles de la comunicación cuando no son conocidos o no son relevantes. Respuesta / Resultado Mensaje Asincrónico Sintaxis del mensaje: Número de secuencia [condición] * [expresión iteración] valor de retorno := nombre del mensaje (parámetros) 293
  • 294. Sequence Diagrams. a1:ClaseA b1:ClaseB [x<0] Op1() :ClaseC [x>0] Op1() X 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. 294
  • 295. Sequence Diagrams. a1:Order b1:OrderLine OrderTotal() *[for each] subtotal() Sintaxis: * [expresión-iteación ] mensaje 295
  • 297. Sequence Diagrams. Activation boxes represent the time an object needs to complete a task 297
  • 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. 298
  • 299. Sequence Diagrams. Lifelines are vertical dashed lines that indicate the object's presence over time. 299
  • 300. Sequence Diagrams. Objects can be terminated early using an arrow labeled "< < destroy > >" that points to an X. 300
  • 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 [ ]. 301
  • 302. Example: 302
  • 303. Example: 303
  • 304. Example: 304
  • 305. Example: 305
  • 306. Example: 306
  • 307. Example: 307
  • 308. Example: 308
  • 309. Example: 309
  • 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. 310
  • 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. 311
  • 312. Sequence Diagrams. GENERAR EL DIAGRAMA DE SECUENCIA PARA LA MAQUINA RECICLADORA. 312
  • 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 314
  • 318. Arrays
  • 319. Declaring arrays. • 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. 319
  • 320. Declaring arrays. • 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; } 320
  • 321. Initializing Arrays. • 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) }; 321
  • 322. Multidimensional Arrays. • Arrays of arrays: int twoDim [][] = new int [4][]; twoDim[0] = new int[5]; twoDim[1] = new int[5]; int twoDim [][] = new int [][4]; illegal 322
  • 325. Multidimensional Arrays. • 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]; 325
  • 326. Array Bounds. • All array subscripts begin at 0: int list[] = new int [10]; for (int i = 0; i < list.length; i++) { System.out.println(list[i]); } 326
  • 327. Array Resizing. • 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]; 327
  • 331. Subclassing 331
  • 332. Subclassing 332
  • 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>* } 333
  • 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 336
  • 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. 338
  • 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. 339
  • 340. Virtual Method Invocation • Virtual method invocation: Employee e = new Manager(); e.getDetails(); • Compile-time type and runtime type 340
  • 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 341
  • 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(); 342
  • 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. 344
  • 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. 345
  • 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. 346
  • 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 { ... } 348
  • 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. 349
  • 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. 350
  • 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.” 353
  • 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) 354
  • 355. Class Attributes • You can invoke static method without any instance of the class to which it belongs. 355
  • 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. 356
  • 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. 357
  • 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>* } 358
  • 359. Interfaces 359
  • 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 361
  • 362. Review. Classes in Java may have methods and attributes. – Methods define actions that a class can perform. – Attributes describe the class. 362
  • 363. Review. 363
  • 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. 364
  • 365. Review. 365
  • 366. Review. 366
  • 367. Review. • Inheritance - a Fish is Also a Pet 367
  • 368. Review. 368
  • 369. Review. 369
  • 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. 370
  • 371. Inheritance. 371
  • 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. 372
  • 377. Inheritance Hierarchy. Animal Cat Dog Horse 377
  • 382. Overriding. 382
  • 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. 384
  • 385. Dynamic Binding and Polymorphism. 385
  • 386. Dynamic Binding and Polymorphism. 386
  • 387. Dynamic Binding and Polymorphism. 387
  • 388. Dynamic Binding and Polymorphism. 388
  • 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). 392
  • 393. Interfaces. 393
  • 394. Interfaces. 394
  • 395. Interfaces. 395
  • 397. Exceptions. • 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 397
  • 398. Exceptions. • 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 398
  • 399. The Exceptions Hierarchy • 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 399
  • 401. Handling Exceptions • Checked exceptions must be either handled in the method where they are generated, or delegated to the calling method 401
  • 402. Keywords • 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) 402
  • 403. try/catch blocks • 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 403
  • 404. The catch clause • 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 404
  • 405. Example 405
  • 406. Example 406
  • 407. The finally clause • 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 407
  • 408. Example 408
  • 409. Nested Exception Handling • 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 409
  • 410. The throw keyword • 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 410
  • 411. Handling runtime exceptions • 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 411
  • 412. Assertions • 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 412
  • 413. Using assertions • 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 413
  • 414. When to use assertions • 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 414
  • 415. When to use assertions • 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 415
  • 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 417
  • 418. Abstract Window Toolkit (AWT). 418
  • 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. 419
  • 420. Containers. 420
  • 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. 421
  • 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. 422
  • 423. Frames. 423
  • 424. Frames. 424
  • 425. Frames. 425
  • 426. Frames. 426
  • 427. Frames. 427
  • 428. Frames. 428
  • 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. 429
  • 432. Containers Layouts. • FlowLayout • BorderLayout • GridLayout • CardLayout • GridBagLayout 432
  • 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 434
  • 438. The BorderLayout Manager. Default layout for the Frame class Components added to specific regions. 438
  • 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. 443
  • 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 449
  • 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. 450
  • 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. 451
  • 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. 452
  • 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. 454
  • 455. How to create a menu. 455
  • 456. How to create a menu. 456
  • 457. How to create a menu. 457
  • 458. How to create a menu. 458
  • 460. Processes and Threads. • 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 460
  • 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 461
  • 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 462
  • 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() ... 463
  • 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(); ... 464
  • 465. Example: subclassing the Thread class. 465
  • 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 466
  • 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 467
  • 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; ......... } 468
  • 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 470
  • 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 471
  • 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 472
  • 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 473
  • 474. Multi-Threading: need for synchronization 474
  • 475. Multi-Threading: need for synchronization 475
  • 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() 476
  • 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. 478
  • 479. What Is a Stream?. 479
  • 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. 480
  • 481. What Is a Stream?. 481
  • 482. What Is a Stream?. 482
  • 483. What Is a Stream?. 483
  • 484. What Is a Stream?. 484
  • 485. What Is a Stream?. 485
  • 487. Converting a Byte Stream into a Character Stream. 487
  • 488. Wrapper Streams. Wrapping streams allows you to create more efficient programs. 488
  • 490. I/O Objects in Java. 490
  • 492. File I/O. Using FileReader and FileWriter you can read from and write to files. 492
  • 495. Microsoft® SQL Server™ es una base de datos relacional cliente-servidor basada en el Lenguaje de consulta estructurado (SQL, Structured Query Language). 495
  • 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. 496
  • 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. 497
  • 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). 498
  • 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. 499
  • 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). 500
  • 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. 501
  • 502. Base de datos relacional (Tablas). Las tablas están compuestas de columnas y filas (atributos y tuplas en la teoría relacional). Columna Tupla, fila id nombre Descripción tamaño Atributos 300 Camisa Cuello V Ch 301 Camisa Ovalada M 302 Camisa Manga Corta S 502
  • 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. 503
  • 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. 504
  • 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. 505
  • 506. Aplicaciones Cliente Cliente-servidor. SQL Server Administrador Base de Usuario Datos Usuario 506
  • 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. 507
  • 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). 508
  • 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). 509
  • 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. 510
  • 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. 511
  • 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. 512
  • 513. 513
  • 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 514
  • 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. 515
  • 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. 516
  • 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. 517
  • 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. 518
  • 519. Una Tabla debe Tener un Identificador PK Llave primaria 519
  • 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. 520
  • 521. Columna 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 Columna Identity Not Null Null 521
  • 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. 522
  • 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. 523
  • 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. 524
  • 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. 525
  • 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. 526
  • 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. 527
  • 528. 528
  • 529. Definición de objetos de una base de datos. CREATE object_name. ALTER object_name. DROP object_name. 529
  • 530. LMD se usa para recuperar datos de la base de datos. SELECT INSERT UPDATE DELETE 530
  • 531. Para crear una tabla. Create Table <Table_Name> ( Column_Name tipoDeDato (identity | Null | Not Null), [...más columnas separadas por comas...] ) 531
  • 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 Tipo de Null o Columna Dato Not Null 532
  • 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] 533
  • 534. Agregando y eliminando columnas. ELIMINAR COLUMNAS ALTER TABLE tabla DROP nombre_columna <tipo> [NULL | NOT NULL] 534
  • 535. Agregando y eliminando columnas. ALTER TABLE empleado ADD rfc char(10) null empID nombre apPaterno apMaterno rfc ALTER TABLE empleado DROP COLUMN apMaterno 535
  • 536. Borrado de una tabla. DROP TABLE tabla Ejemplo: DROP TABLE empleado 536
  • 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’) 537
  • 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. 538
  • 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 539
  • 540. RECUPERAR DATOS. SELECT nombre FROM empleado SELECT nombre,apPaterno,apMaterno FROM empleado SELECT nombre,apPaterno FROM empleado WHERE nombre=‘Juan’ 540
  • 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. 541
  • 542. ACTUALIZAR DATOS. UPDATE empleado SET apMaterno=‘el mismo para todos’ UPDATE empleado SET nombre=‘Raul’ WHERE nombre=‘Juan’ 542
  • 543. ELIMINANDO DATOS. La instrucción DELETE se usa para eliminar datos de una tabla. EJEMPLO: DELETE FROM empleado WHERE nombre=‘Raul’ 543
  • 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: 544
  • 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 545
  • 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. 546
  • 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. 547
  • 548. RESTRICCIONES DE CLAVE PRINCIPAL. CREATE TABLE Autores Tabla sin llave primaria ( AutorID not null, Nombre not null, Apellido not null, AñoNac null, AñoMuerte null, Descripcion null ) 548
  • 549. RESTRICCIONES DE CLAVE PRINCIPAL. CREATE TABLE Autores Tabla con llave primaria ( AutorID not null, Nombre not null, Apellido not null, AñoNac null, AñoMuerte null, Descripcion null, CONSTRAINT autor_pk PRIMARY KEY(AutorID) ) Nombre de la llave primaria 549
  • 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. 550
  • 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) ) 551
  • 552. RESTRICCIONES DE CLAVE EXTERNA. CREATE TABLE Libros ( Tabla sin FK LibroID char(8) not null, Titulo varchar(60) not null, Editor varchar(60) null, FechaEd date null, Costo float not null, CondicionID no tiene ninguna CondicionID int not null, celación con el otro nombre de Vendido char(2) null Columna de la tabla ) LibroEstado 552
  • 553. RESTRICCIONES DE CLAVE EXTERNA. CREATE TABLE Libros ( Tabla con FK 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) DE LA TABLA ) LIBROESTADO 553
  • 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: 554
  • 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. 555
  • 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), ) 556
  • 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), ) 557
  • 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. 558
  • 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. 559
  • 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), Restricción check CondicionID int not null, Vendido char(2) null, CONSTRAINT libro_pk PRIMARY KEY(CondicionID), FOREIGN KEY(CondicionID) REFERENCES LibroEstado(CondicionID) ) 560
  • 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. 561
  • 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. 562
  • 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), ) 563
  • 565. Diseño de una aplicación Java con acceso a Base de Datos. 565
  • 566. Bases de Datos Relacionales. 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). 566
  • 567. Bases de Datos Relacionales. 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) ) 567
  • 568. Bases de Datos Relacionales. 3. Configurar el DSN del usuario y del sistema con el nombre lógico EjemploJava. 568
  • 569. Bases de Datos Relacionales. 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. 569
  • 570. Bases de Datos Relacionales. CONSULTAR DATOS. SELECT * FROM CLIENTE SELECT nombreCliente, ocupacion FROM CLIENTE SELECT nombreCliente FROM CLIENTE SELECT nombreCliente FROM CLIENTE WHERE ocupacion=“profesor” 570
  • 571. Bases de Datos Relacionales. BORRAR DATOS. DELETE FROM Cliente Where ocupacion=“estudiante” DELETE FROM Cliente 571
  • 572. Bases de Datos Relacionales. MODIFICAR DATOS. UPDATE Cliente SET ocupacion=“estudiante” WHERE ocupacion=“actor” UPDATE Cliente SET ocupacion=“actor” WHERE nombreCliente=“Juan Perez” 572
  • 573. Arquitectura de la aplicación. 573
  • 574. Arquitectura de la aplicación. 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). 574
  • 575. Arquitectura de la aplicación. . 575
  • 576. Arquitectura de la aplicación. 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. 576
  • 577. Arquitectura de la aplicación. El siguiente gráfico muestra la arquitectura del sistema de vista desde el nivel de aplicación, usando Java. 577
  • 578. Arquitectura de la aplicación. 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. 578
  • 579. Arquitectura de la aplicación. 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. 579
  • 580. Arquitectura de la aplicación. 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. 580
  • 581. Conexión a una base de datos. 581
  • 582. Conexión a una base de datos. 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. 582
  • 583. Conexión a una base de datos. Las clases e interfaces que utilizaremos se encuentran en el paquete java.sql 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: 583
  • 584. Conexión a una base de datos. Primero establecemos el driver a utilizar (ODBC) que nos proporciona la biblioteca JDBC. 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: 584
  • 585. 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. 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: 585
  • 586. 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. 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: 586
  • 587. Conexión a una base de datos. Utilizando el método createStatement, perteneciente al objeto de tipo Connection, creamos el objeto de tipo Statement. 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: } 587 25:}
  • 588. 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. 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: } 588 25:}
  • 589. 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. 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: } 589 25:}
  • 590. 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. 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: } 590 25:}
  • 592. Consultas y ResultSet. 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. 592
  • 593. Consultas y ResultSet. 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(); 593
  • 594. Consultas y ResultSet. 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("**********"); } 594
  • 595. Consultas y ResultSet. cliente.close(); conexion.close(); sentenciaSQL.close(); } catch (ClassNotFoundException e) { System.out.println("Clase no encontrada"); } catch (SQLException e ) { System.out.println(e); } } } 595
  • 597. Actualizaciones. 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); 597
  • 598. Actualizaciones. 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); } } } 598
  • 599. Inserción. 599
  • 600. Inserción. 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"; 600
  • 601. Inserción. 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);} } } 601
  • 602. Borrado. 602
  • 603. Borrado. 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+"'"; 603
  • 604. Borrado. 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);} } } 604