SlideShare a Scribd company logo
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
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020
P J020

More Related Content

Similar to P J020

Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
VAIBHAVKADAGANCHI
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
Martin Odersky
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
Neetu Mishra
 
Subprogram
SubprogramSubprogram
Subprogram
baran19901990
 
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive SystemsGo Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Jonas Bonér
 
Oop(object oriented programming)
Oop(object oriented programming)Oop(object oriented programming)
Oop(object oriented programming)
geetika goyal
 
Java script
Java scriptJava script
Java script
Prarthan P
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison
 
core_java.ppt
core_java.pptcore_java.ppt
core_java.ppt
YashikaDave
 
Bound and Checked
Bound and CheckedBound and Checked
Bound and Checked
Kevlin Henney
 
Java introduction
Java introductionJava introduction
Java introduction
GaneshKumarKanthiah
 
Lecture1
Lecture1Lecture1
Lecture1
Amisha Dalal
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
Hawkman Academy
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
SURBHI SAROHA
 
New c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_ii
Nico Ludwig
 
Predictable reactive state management - ngrx
Predictable reactive state management - ngrxPredictable reactive state management - ngrx
Predictable reactive state management - ngrx
Ilia Idakiev
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
Dhaval Dalal
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
Steve Johnson
 

Similar to P J020 (20)

73d32 session1 c++
73d32 session1 c++73d32 session1 c++
73d32 session1 c++
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
 
Subprogram
SubprogramSubprogram
Subprogram
 
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive SystemsGo Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
Go Reactive: Event-Driven, Scalable, Resilient & Responsive Systems
 
Csharp
CsharpCsharp
Csharp
 
Oop(object oriented programming)
Oop(object oriented programming)Oop(object oriented programming)
Oop(object oriented programming)
 
Java script
Java scriptJava script
Java script
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
core_java.ppt
core_java.pptcore_java.ppt
core_java.ppt
 
Bound and Checked
Bound and CheckedBound and Checked
Bound and Checked
 
Java introduction
Java introductionJava introduction
Java introduction
 
Lecture1
Lecture1Lecture1
Lecture1
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
C language (Part 2)
C language (Part 2)C language (Part 2)
C language (Part 2)
 
New c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_ii
 
Predictable reactive state management - ngrx
Predictable reactive state management - ngrxPredictable reactive state management - ngrx
Predictable reactive state management - ngrx
 
Booting into functional programming
Booting into functional programmingBooting into functional programming
Booting into functional programming
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 

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