fundamento java
Post on 23-Nov-2015
87 Views
Preview:
TRANSCRIPT
-
PJ-020
FUNDAMENTOS DE JAVA www.profesorjava.com
-
Esta obra est bajo una licencia Reconocimiento 2.5 Mxico de Creative Commons. Para ver una copia de esta licencia, visite http://creativecommons.org/licenses/by/2.5/mx/ o enve una carta a Creative Commons, 171 Second Street, Suite 300, San Francisco, California 94105, USA.
-
Acerca de: En la compilacin de esta obra se utilizaron libros conocidos en el ambiente Java, grficas, esquemas, figuras de sitios de internet, conocimiento adquirido en los cursos oficiales de la tecnologa Java. En ningn 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 intencin 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 ms completo que pueda servir para divulgar el conocimiento.
Atte. ISC Ral Oramas Bustillos.
rauloramas@profesorjava.com
-
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 Programs Execution Flow.
Exercises
Java Language Basics
-
Anatomy of a Simple Java Program.
Comments
class wrapper
main
method
-
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 prdida de precisin
int valor;
long valor2 = 123987654321;
valor = (int)valor2; //el nmero 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 Programs Execution Flow.
if
while
do
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 Programs Execution Flow. If
-
Controlling a Programs Execution Flow. If
-
Controlling a Programs Execution Flow. If
-
Controlling a Programs Execution Flow. If
-
Controlling a Programs Execution Flow. If
-
Controlling a Programs Execution Flow. If-else: ?
Shortcut for if-else statement:
( ? : )
Can result in shorter code
Make sure code is still readable
-
Controlling a Programs 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 Programs Execution Flow. Switch
-
Controlling a Programs 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 methods return type Return type void means no value can be returned
-
Branching statements
-
Branching statements
-
Abstraction and Modeling
-
57
Simplification Through Abstraction
Generalization Through Abstraction
Reuse of Abstractions
Inherent Challenges
Exercises
Abstraction and Modeling
-
58
Abstraction: a process that involves recognizing and focusing
on the important characteristics of a situation or object, and
filtering out or ignoring all of the unessential details.
Is the process of ignoring details to concentrate on essential characteristics
Is the primary means of coping with complexity
Simplifies users interaction with abstracted objects
Simplification Through Abstraction
-
59
Simplification Through Abstraction
-
60
One familiar example of an abstraction is a road map.
Simplification Through Abstraction
-
61
As an abstraction, a road map represents those features of a given geographic
area relevant to someone trying to navigate with the map, perhaps by a car:
major roads and places of interest, obstacles such as major bodies of water, etc.
Of necessity, a road map cannot include every building, tree, street sign,
billboard, traffic light, fast food restaurant, etc. that physically exists in the real
world. If i did, then it would be so cluttered as to be virtually unusable; none of
the important features would stand out.
Simplification Through Abstraction
-
62
Compare a road map with a topographical map, a climatological
map, and a population density map of the same region: each
abstracts out different features of the real world namely, those
relevant to the intender user of the map in question.
Simplification Through Abstraction
-
63
As another example, consider a landscape. An artist may look at the landscape
from the perspective of colors, textures, and shapes as a prospective subject for
a painting.
Simplification Through Abstraction
-
64
A homebuilder may look at the same landscape from the perspective of where
the best building site may be on the property, assessing how many trees will need
to be cleared to make way for a construction project.
Simplification Through Abstraction
-
65
Simplification Through Abstraction
-
66
If we eliminate enough detail from an abstraction, it becomes
generic enough to apply to a wide range of specific situations
or instances. Such generic
abstractions can often be
quite useful. For example,
a diagram of a generic cell
in the human body might
include only a few features
of the structures that
are found in an actual cell:
Generalization Through Abstraction
-
67
This overly simplified diagram doesnt look like a real nerve cell, or a real
muscle cell, or a real blood cell; and yet, it can still be used in a educational
setting to describe certain aspects of the structure and function of all of these
cell types namely, those features that the various cell types have in common.
Generalization Through Abstraction
-
68
Even though our brains are adept at abstracting concepts such as road maps and
landscapes, that still leaves us with hundreds of thousands, if not millions, of
separate abstractions to deal with over our lifetimes. To cope with this aspect of
complexity, human beings systematically arrange information into categories to
established criteria; this process is known as classification.
Organizing Abstractions Into Classification Hierarchies
-
69
Organizing Abstractions Into Classification Hierarchies
-
70
Organizing Abstractions Into Classification Hierarchies
-
71
For example, science categorizes all natural objects as belonging to either the
animal, plant, or mineral kingdom. In order for a natural object to be classified
as an animal, it must satisfy the following rules:
It must be a living being
It must be capable of spontaneous movement
It must be capable of rapid motor response to stimulation
Organizing Abstractions Into Classification Hierarchies
-
72
The rules for what constitute a plant, on the other hand, are diferent:
It must be a living being (same as for an animal)
It must lack an obvious nervous system
It must possess cellulose cell walls
Organizing Abstractions Into Classification Hierarchies
-
73
Given clear-cut rules such as these, placing an object into the appropriate
category, or class, is rather straightforward. We can then drill down,
specifying additional rules which differentiate various types of animal, for
example, until weve built up a hierarchy of increasing more complex
abstractions from top to bottom.
Organizing Abstractions Into Classification Hierarchies
-
74
A simple example of an abstraction hierarchy is shown below.
Organizing Abstractions Into Classification Hierarchies
Natural Objects
Plant Animal Mineral
Mammal Fish Bird Reptile Insect
Dog Cat Monkey
-
75
When thinking about an abstraction hierarchy such as the one shown previously,
we mentally step up and down thehierarchy, automatically zeroing in on only the
single layer or subset of the hierarchy (known as a subtree) that is important
to us at a given point in time. For example, we may only be concerned with
mammals, and so can focus on the mammalian subtree:
Organizing Abstractions Into Classification Hierarchies
Mammal
Dog Cat Monkey
-
76
We temporarily ignore the rest of the hierarchy. By doing so, we automatically
reduce the number of concepts that we mentally need to juggle at any one
time to a manageable subset of the overall abstraction hierarchy; in the
simplistic example, we are now dealing with only four concepts rather than the
original 13. No matter how complex an abstraction hierarchy grows to be, it
neednt overwhelm us if it is properly organized.
Organizing Abstractions Into Classification Hierarchies
Mammal
Dog Cat Monkey
-
77
Coming up with precisely which rules are necessary to properly classify an object
within an abstraction hierarchy is not always easy. Take for example, the rules
we might define for what constitutes a bird: namely, something which:
Has feathers
Has wings
Lays eggs
Is capable of flying
Organizing Abstractions Into Classification Hierarchies
-
78
Given these rules, neither an ostrich nor a penguin could be classified as a bird,
because neither can fly.
Organizing Abstractions Into Classification Hierarchies
Birds Non-Birds
-
79
If we attempt to make the rule set less restrictive by eliminating the flight
rule, we are left with:
Has feathers
Has wings
Lays eggs
According to this rule set, we now may properly classify both the ostrich and the
penguin as birds.
Organizing Abstractions Into Classification Hierarchies
-
80
Organizing Abstractions Into Classification Hierarchies
Birds Non-Birds
-
81
This rule set is still unnecessarily complicated, because as it turns out, the lays
eggs rule is redundant: whether we keep it or eliminate it, it doesnt change our
decision of what constitutes a bird versus a non-bird. Therefore, we simplify
the rule set once again:
Has feathers
Has wings
Organizing Abstractions Into Classification Hierarchies
-
82
We try to take our simplification process one step further, by eliminating yet
another rule, defining a bird as something which:
Has wings
Weve gone too far this time: the abstraction of a bird is now so general that
wed include airplanes, insects, and all sorts of other non-birds in the mix.
Organizing Abstractions Into Classification Hierarchies
-
83
Organizing Abstractions Into Classification Hierarchies
The process of rule definition for purposes of categorization
involves dialing in just the right set of rules not too general, not to restrictive, and containing no redundancies- to define
the correct membership in a particular class.
-
84
When pinning down the requirements for an information systems development
project, we typically start by gathering details about the real world definition on
which the system is to be based. These details are usually a combination of:
Those that are explicitly offered to us as we interview the intended users of the system
Those that we otherwise observe.
Abstractions as the Basis for Software Development
-
85
We must make a judgment all as to which of these details are relevant to the
systems ultimate purpose. This is essential, as we cannot automate them all!.
To include too much details is to overly complicate the resultant system, making
it that much more difficult to design, program, test, debug, document, maintain,
and extend in the future.
As with all abstractions, all of our decisions of inclusions versus elimination when
building a software system must be made within the context of the overall
purpose and domain, or subject matter focus, of the future system.
Abstractions as the Basis for Software Development
-
86
Once weve determined the essential aspects of a situation we can prepare a
model of that situation. Modeling is the process by which we develop a pattern
for something to be made. A blueprint for a custom home, a schematic diagram
of a printed circuit, and a cookie cutter are all examples of such patterns.
Abstractions as the Basis for Software Development
-
87
Abstractions as the Basis for Software Development
A model is a simplification of the reality.
-
88
Modeling achieves four aims:
Helps you to visualize a system as you want it to be.
Permits you to specify the structure or behavior of a system.
Gives you a template that guides you in constructing a system.
Documents the decisions you have made.
You build models of complex systems because you cannot comprehend such a system in its entirety.
You build models to better understand the system you are developing.
Abstractions as the Basis for Software Development
-
89
The importance of modeling:
Abstractions as the Basis for Software Development
Paper Airplane Fighter Jet
Less Important More Important
-
90
Many software teams build applications approaching the problem like they were building paper airplanes
Start coding from project requirements
Work longer hours and create more code
Lacks any planned architecture
Doomed to failure
Modeling is a common thread to successful projects
Abstractions as the Basis for Software Development
-
91
An object model of a software system is such a pattern. Modeling and
abstraction go hand in hand, because a model is essentially a physical or
graphical portrayal of an abstraction; before we can model something effectively,
we must have determined the essential details of the subject to be modeled.
Abstractions as the Basis for Software Development
-
92
When learning about something new, we automatically search our mental
archive for other abstractions/models that weve previously built and mastered,
to look for similarities that we can build upon.
When learning to ride a two-wheeled
bicycle for the first time, for example,
you may have drawn upon lessons
that you learned about riding a
tricycle as a child.
Reuse of Abstractions
-
93
Both have handlebars that are used to steer; both have pedals that are used to
propel the bike forward. Although the Abstractions didnt match perfectly a
two wheeled bicycle introduced the new challenge of having to balance oneself
there was enough of a similarity to allow you to draw upon the steering and
pedaling expertise you already had mastered, and to focus on learning the new
skill of how to balance on two wheels.
Reuse of Abstractions
-
94
Reuse of Abstractions
This technique of comparing features to find an abstraction
that is similar enough to be reused successfully is known as
pattern matching and reuse. A pattern reuse is an
important technique for object oriented software development
,as well, because it spares us from having to reinvent the
wheel with each new project. If we can reuse an abstraction
or model from a previous project, we can focus on those
aspects of the new project that differ from the old, gaining
a tremendous amount of productivity in the process.
-
95
Pattern matching
Reuse of Abstractions
-
96
Reuse of Abstractions
-
97
Reuse of Abstractions
-
98
Despite the fact that abstraction is such a natural process for human beings,
developing an appropriate model for a software system is perhaps the most
difficult aspect of software engineering.
Inherent Challenges
-
99
Inherent Challenges
-
Objects and Classes
-
101
What is an object?
Methods
Reuse of Abstractions
Inherent Challenges
Exercises
Objects and Classes
-
102
A class is a collection of objects with related properties and behaviours.
In real-life we group things into classes to help us reduce complexity
Example:
The set of all dogs forms the class Dog
Each individual dog is an object of the class Dog
Firulais, Terry and Rex are all instances of the class Dog
To some extent, we can interact with Firulais based on our knowledge of dogs in general, rather than Firulais himself
What Is an Object?
-
103
What Is an Object?
-
104
What is a Waiter?
A Waiter is someone who has the following properties and behaviours:
Properties of a Waiter
Full Name
Behaviours of a Waiter
Bring menus
Take orders
Bring meals
This collection of properties and behaviours defines the class of Waiters
Because these behaviours are standardized, we can deal with any Waiter just based on our general knowledge of Waiters
What Is an Object?
-
105
A class is a general description of the properties and behaviours of some entities.
We described the class Waiter
giving the general description
of what properties Waiters have
and what things Waiters can
do.
What Is an Object?
Waiter
fullName
bringMenu
takeOrder
bringMeal
Name of
class
Properties
Behaviours
-
106
An object is a specific member of a class.
An object belonging to the class of Waiters is an actual individual waiter
Pierre is an object of the class Waiter, and so is Bill and so is Jimmy they can all take orders, bring menus and bring meals
What Is an Object?
-
107
What Is an Object?
-
108
Class Object
What Is an Object?
-
109
What Is an Object?
Classes in Java may have methods and attributes.
Methods define actions that a class can perform.
Attributes describe the class.
-
110
What Is an Object?
-
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.
-
112
What Is an Object?
-
113
What Is an Object?
-
114
What Is an Object?
-
115
The class BankAccount
A bank account has the following properties:
An account number and account name
A balance
A bank account has the following behaviours:
Money can be credited to the bank account
Money can be debited from the bank account
What Is an Object?
-
116
What Is an Object? BankAccount
accountName
accountNumber
credit
debit
-
117
Objects in Java are creating using the keyword new.
What Is an Object?
-
118
The arguments in the constructor are used to specify initial information about
the object. In this case they represent the account number and account name.
A constructor can have any number of arguments including zero.
What Is an Object?
Arguments
-
119
What Is an Object?
1. Declare a reference.
2. Create the object.
3. Assign values.
-
120
What Is an Object?
1. Declare a reference.
2. Create the object.
Two references to two
objects, with values
for their attributes.
-
121
What Is an Object?
-
122
What Is an Object?
Heap memory Stack memory
428802
0x99f311
0x334009 AnotherShirt
myShirt
id
\u0000
0.0
false
\u0000
0.0
false
size
size
price
price
lSleeved
lSleeved
-
123
What Is an Object?
Heap memory Stack memory
0x99f311
0x334009
0x99f311
AnotherShirt
myShirt
\u0000
0.0
false
\u0000
0.0
false
size
size
price
price
lSleeved
lSleeved
X X
-
124
Consider a class that represents a circle.
public class Circle {
int radius;
}
public class ShapeTester {
public static void main(String args[]) {
Circle x;
x = new Circle();
System.out.println(x);
}
}
What Is an Object. Examples.
-
125
Here is another example defining a Rectangle that stores a width and height as
doubles:
public class Rectangle {
double width = 10.128;
double height = 5.734;
}
public class ShapeTester {
public static void main(String args[]) {
Circle x;
Rectangle y;
x = new Circle();
y = new Rectangle();
System.out.println(x + " " + y);
}
}
What Is an Object. Examples.
-
126
public class ShapeTester {
public static void main(String args[]) {
Circle x;
Rectangle y, z;
x = new Circle();
y = new Rectangle();
z = new Rectangle();
System.out.println(x + " " + y + " " + z);
}
}
What Is an Object. Examples.
-
127
public class ShapeTester {
public static void main(String args[]) {
Circle x;
Rectangle y, z;
x = new Circle();
y = new Rectangle();
z = new Rectangle();
x.radius = 50;
z.width = 68.94;
z.height = 47.54;
System.out.println(x.radius + " " + y.width + " " + z.width);
}
}
What Is an Object. Examples.
-
Objects Interactions
-
129
Methods
Exercises
Objects Interactions
-
130
The interesting part of OO-Programming is getting the objects to interact
together. This is obvious when we look at real world examples:
A house not being lived in is not useful
A BankAccount in which no money is deposited or withdrawn is not useful either
A CD without a CD Player is useless too.
Behaviour represents:
the things you can do with an object (i.e., a command)
information you can ask for from an object (i.e., a question)
Methods
-
131
By definition an instance is created from its class definition and so it only uses
the vocabulary defined in its own class. To help us understand object behaviour,
we should try to think of objects as being living entities. When we want to
"talk to" or "manipulate" an object, we must send it a message.
A message:
is a set of one or more words (joined together as one) that is sent to an object.
is part of the "vocabulary" that an object understands.
may have additional information (parameters) which are required by the object.
You can send messages to objects, and they respond to you:
Methods
-
132
May have additional information (parameters) which are required by the object.
You can send messages to objects, and they respond to you:
Objects only respond if they understand what you say:
Methods
-
133
The message may require some parameters (i.e., pieces of data):
Methods
-
134
Thus, by defining behaviour, we simply add to the vocabulary of words (i.e.,
messages) that the object understands. Objects communicate by sending
messages back and forth to each other:
Methods
-
135
As we can see, many objects are often involved in a more difficult task. For
example, consider building a house. A person asks a house building company to
build them a house. In fact, the house building company then "sub-contracts"
out all of the work in that it then hires others to do all the work. So the house
builder actually co-ordinates the interactions with all of the contractors. The
contractors themselves contact suppliers to get their parts as well as other
helpers to help them accomplish their tasks:
Methods
-
136
Methods
-
137
To define a particular behaviour for an object, we must write a method
A method :
is the code (expressions) that defines what happens when a message is sent to an object.
may require zero or more parameters (i.e., pieces of data):
Parameters may be primitives or other objects
Primitives are passed-by-value (the actual value is copied and passed with the message)
Objects are passed-by-reference (a pointer to the object is passed with the message)
may be either a class method or an instance method.
Methods are typically used to do one or more of these things:
get information from the object it is sent to change the object in some way
compute or do something with the object
obtain some result.
Methods
-
138
Methods are typically used to do one or more of these things:
get information from the object it is sent to
change the object in some way
compute or do something with the object
obtain some result.
Methods
-
139
Methods
-
140
Sending a message to an object is also known as calling a method. So the
method is actually the code that executes when you send a message to an
object. Some methods return answers, others may do something useful but do
not return any answer.
Methods
-
141
A method is calling by specifying
The target object, following by a dot
The method name
The method arguments (is there are any)
cheque.getBalance();
The target object is the one called cheque
The getBalance method has been called
There are no arguments for this method
The result will be returned to whoever called the method
Methods
-
142
Methods
-
143
Methods
-
144
Methods
-
145
Methods
-
146
Methods
Calling its method
-
147
In general, methods calls may
Send information to the target, or not
Receive information from the object, or not
The method signature tell us whether information is to be sent,
received or both.
Methods
-
148
Methods
-
149
Methods
-
150
Methods
-
Collection of Objects
-
152
Data Structures.
A data structure can be thought of as container that is used to
group multiple elements into a single representation, and is
used to store, retrieve, and manipulate the contained data.
-
153
Basic Data Structure Mechanisms.
Before the development of the Java2 platform, only a small set
of classes and interfaces were available in the supplied
Standard Class. Library for data store manipulation.
Arrays
Vector
Stack
Hashtable
Properties
BitSet
Enumeration
-
154
The Vector Class.
Contains a collection of object references.
Can vary in size.
Can hold objects of different types.
The Vector class is more flexible than an Array:
-
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
The Vector Class.
-
165
HashTable.
Maps keys to values
Keys and values can be any non-null object
-
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()
-
167
Enumeration Interface.
-
168
The Collection API.
-
169
The Collection API.
-
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.
-
171
HashSet Class.
-
172
TreeSet Class.
-
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()
-
174
Iterator Interface.
-
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.
-
176
List Interface.
-
177
ListIterator Interface.
-
178
LinkedList Class.
-
179
LinkedList Class.
-
180
Concrete Collections.
-
Objects 1
-
1. Objects
-
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 Managers Guide, Taylor, 1997)
-
184
Overview of Object Orientation.
-
185
Identifying Objects.
Object can be a sentence, bank account, number, or car
Objects are:
Things
Real or imaginary
Simple or complex
An object is an entity with a well-defined boundary and
identity that encapsulates state and behavior.
-
186
Identifying Objects.
An object is an entity with a well-defined boundary and
identity that encapsulates state and behavior.
-
187
Identifying Objects.
-
188
Identifying Objects.
Physical entity
Conceptual entity
(Chemical process)
Software entity
(Linked list)
-
189
Identifying Objects.
Objects have many forms:
Tangible things (Airplane, Computer, Car)
Roles (Doctor, Teacher)
Incidents (Meeting)
Interactions (Interview, Agreement)
-
190
Object definition. Case Study
Throughout this course, a case study of a clothing catalog, DirectClothing, Inc., will be used to illustrate concepts.
-
191
Object definition. Case Study
Most projects start by defining the problem domain by gathering customer requirements and by writing a statement of scope that briefly states what
you, the developer, want to achieve.
For example, a scope statement for the DirectClothing project might be: Create a system allowing order entry people to enter and accept payment for an order.
After you have determined the scope of the project, you can begin to identify the objects that will interact to solve the problem.
-
192
Object definition. Case Study
Object names are often nouns, such as account or shirt. Object attributes are often nouns too, such as color or size. Object operations are usually verbs or noun-verb combinations, such asdisplay or submit order.
Your ability to recognize objects in the world around you will help you to better define objects when approaching a problem using object-oriented
analysis.
Solution
-
193
Object definition. Case Study
The problem domain of the DirectClothing, Inc. case study has the following nouns. Each could be an object in the catalogs order entry system.
catalog
clothing
subscribers
closeout items
monthly items
normal items
order
-
194
Object definition. Case Study
customer
CSR ( customer service representative)
order entry clerk
Supplier
Payment
warehouse
credit car
order entry
mail order
fax order
online order
-
195
Object definition. Case Study
inventory
back-ordered items
system
Internet
business
year
month
order form
check
-
196
Identifying Object Attributes and Operations
Example:
Cloud attributes: size, water content, shape
Cloud operations: rain, thunder, snow
Attributes: an objects characteristics Operations: what an object can do
-
197
Identifying Object Attributes and Operations
-
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 objects operations.
-
199
Identifying Object Attributes and Operations. Case Study
For the Order object, the following attributes and operations could be defined:
Attributes: orderNumber, customerNumber, dateOrdered, amountOwed
Operations: whatCustomer, calcAmountOwed, printOrder, payOrder
What would be the attributes and operations for the Customer object?
-
200
Testing an Identified Object:
Use the following criteria to test object validity:
Relevance to the problem domain
Need to exist independently
Having attributes and operations
-
201
Relevance to the Problem Domain.
Does it exist within the boundaries of the problem statement?
Is it required in order for the system to fulfill its responsibility?
Is it required as part of interaction between a user and the system?
Can objects sometimes be a characteristic of other objects?
-
202
Testing an Identified Object. Case Study
The Order object exists within the boundaries of the problem statement, it is required for the system to fulfill its responsibilities, and as part of an
interaction between a user and the system. The Order object passes the test.
Test the other candidate objects in the case study. What are the results?
-
203
Testing an Identified Object. Case Study
The following objects can probably be removed from the list:
Internet, system, business Not necessary within the boundaries of the problem statement
month, year May be attributes of the date of an order being placed, but not necessary as an object itself
-
204
Testing an Identified Object. Case Study
The following objects can probably be removed from the list:
online order, fax order, mail order Can probably be captured as special cases of the order object, or you could have a type attribute on the order object to
indicate how the order was made. You may not want to eliminate here, but to
note these nouns are special cases.
back-ordered items, closeout items, monthly sales item Can probably be captured as special cases of a normal item object. You may not want to
eliminate these nouns, but to note these are special cases.
-
205
Independent Existence.
To be an object and not a characteristic of another object, the object must need to exist independently
-
206
Independent Existence. Case Study
Can an Order object exist without any of the other objects? It can, but in use, it must have an associated Customer object.
Address could be an attribute of Customer, but in this case study it is advantageous for Address to be a separate object.
-
207
Attributes and Operations.
An object must have attributes and operations
If it does not, it is probably and attribute or operation of another object
-
208
Attributes and Operations. Case Study
An object must have attributes and operations. If you cannot define attributes and operations for an object, then it probably is not an object but an
attribute or operation of another object.
The Order object has many attributes and operations defined, as do most of the candidate objects.
-
209
Encapsulation.
Encapsulation separates the external aspects of an object from the internal implementation details
Internal changes need not affect external interface
Hide
implementation
from clients.
Clients depend
on interface
-
210
Encapsulation.
-
211
Implementing Encapsulation.
An objects 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
-
Objects 2
-
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 Managers Guide, Taylor, 1997)
-
214
Class Overview.
A class is a description of a set of objects that share the same attributes, operations, relationships, and semantics.
An object is an instance of a class.
A class is an abstraction in that it Emphasizes relevant characteristics. Suppresses other characteristics.
-
215
Class Overview.
An object is an instance of a class.
-
216
Class Overview.
A class is represented using a rectangle with compartments.
-
217
Class Overview.
A class is an abstract definition of an object. It defines the structure and behavior of each object in the class. It serves as a template for creating
objects.
Classes are not collections of objects.
-
218
Class Overview.
An attribute is a named property of a class that describes a range of values that instances of the property may hold.
A class may have any number of attributes or no attributes at all.
-
219
Class Overview.
An operation is the implementation of a service that can be requested from any object of the class to affect behavior.
A class may have any number of operations or none at all.
-
220
Generalization
Generalization identifies and defines the common attributes
and operations in a collection of objects.
Example: Transport is a generalization of several classes that
provide transportation.
-
221
Generalization
A relationship among classes where one class shares the
structure and/or behavior of one or more classes.
-
222
Inheritance
Is a mechanism for defining a new class in terms of an existing class.
Allows you to group related classes so that they can be managed collectively.
Promotes reuse.
Allows you to hide or override inherited members.
Relevant terms: generalization, specialization, override.
-
223
Inheritance
-
224
Inheritance
-
225
Inheritance
-
226
Inheritance
-
227
Specialization
Specialization is inheritance with the addition and modification
of methods to solve a specific problem.
-
228
Polymorphism
Allows you to implement an inherited operation in a subclass
Works only when the common operation gives the same semantic result
Implementation of a polymorphic function depends on the object it is applied to
Can be used only with inheritance
-
229
Polymorphism
Polymorphism is the ability to hide many different
implementations behind a single interface.
-
230
Polymorphism
Interfaces formalize polymorphism.
-
Objects 3
-
232
Object Messaging.
One object sends a message to another (the receiving object)
The receiving object may send other messages, change its attribute, or read in any other appropriate way.
Messaging in handled by operations in the public interface of the receiving object.
-
233
Association and Composition.
Objects interact through one of two relationships: association or composition.
Association: Two independent objects collaborate to achieve some goal, like a person using a computer (uses a relationship)
Composition: One object contains another, like a pencil that has a lead (has a relationship)
-
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
Association and Composition.
a
-
Objects 4
-
248
Object-Oriented Analysis and Design.
Unified Modeling Language (UML) is used to notate the design.
UML diagrams:
Use case diagram
Sequence diagram
Class diagrams
Activity diagrams
-
249
Use Case Diagrams.
A use case diagram contains use cases, actors, and relationship links
A use case is an interaction of a user with the application in order to achieve a desired result
An actor is a role that a user plays when interfacing with the application
Relationship links between use cases are uses and extends.
-
250
Use Case Diagrams.
There are two types of relationship links that can be made in the diagram. These are the extends and uses relationships between the use cases.
The extends relationship links two use cases that are similar but one does a little more than the other. It is implied that the actor who performs the first
use case will also perform the extension use case. This relationship is
indicated by on the links line.
-
251
Use Case Diagrams.
The second type of link is the uses relationship, which occurs when there is a behavior that is used by many use cases. To avoid repetition, make that
behavior a use case itself, and have other use cases use it. It is implied that an actor does not perform the used use case, but that the base use case does the performing.
This relationship is indicated by on the links line.
-
252
Use Case Diagrams.
An actor represents anything that interacts with the system.
A use case is a sequence of actions a system performs that yields an observable result of value to a particular actor.
-
253
Use Case Diagrams.
-
254
Use Case Diagrams.
-
255
Use Case Diagrams.
Follow these steps to create a use case diagram:
1. Identify each use case in your application. (It might help to identify events
you need to react to.)
2. Draw and label each of the actors of the application.
3. Draw and label the use cases of the application.
4. Draw the links from the actor to the use cases they perform.
5. Write a short description of each use case. The diagram and the description
together will give a representation of the functionality that must be
implemented in the system.
-
256
Example: Use Case Diagrams.
A use case specifies a set of scenarios
for accomplishing something
useful for an actor. In this
example, one use case is
"Buy soda."
-
257
Example: Use Case Diagrams.
Restocking a soda machine is an important use case.
-
258
Example: Use Case Diagrams.
Collecting the money
from a soda machine
is another
important use case.
-
259
Example: Use Case Diagrams.
-
260
Use Case Diagrams.
Use case diagrams describe what a system does from the
standpoint of an external observer. The emphasis is on what
a system does rather than how.
Use case diagrams are closely connected to scenarios. A
scenario is an example of what happens when someone
interacts with the system.
-
261
Use Case Diagrams.
Here is a scenario for a medical clinic:
"A patient calls the clinic to make an appointment for a
yearly checkup. The receptionist finds the nearest empty time
slot in the appointment book and schedules the appointment
for that time slot. "
-
262
Use Case Diagrams.
A use case is a summary of scenarios for a single task or
goal. An actor is who or what initiates the events involved in
that task. Actors are simply roles that people or objects play.
The picture below is a Make Appointment use case for the
medical clinic. The actor is a Patient. The connection between
actor and use case is a communication association (or
communication for short).
-
263
Use Case Diagrams.
A use case diagram is a collection of actors, use cases, and
their communications. We've put Make Appointment as part of
a diagram with four actors and four use cases. Notice that a
single use case can have multiple actors.
-
264
Use Case Diagrams.
A use case describes a single task or goal and is indicated by
an oval. The task or goal is written inside the oval and usually
it contains a verb.
-
265
Use Case Diagrams.
TIP: Start by listing a sequence of steps a user might take in
order to complete an action. For example a user placing an
order with a sales company might follow these steps.
1. Browse catalog and select items.
2. Call sales representative.
3. Supply shipping information.
4. Supply payment information.
5. Receive conformation number from salesperson.
-
266
Use Case Diagrams.
-
267
Exercises: Use Case Diagrams.
Disear diagramas de casos de uso para las siguientes
situaciones:
Comprar una paleta en la cafetera de la escuela.
Cancelar una cita con el(la) novio(a) una salida con los amigos.
Enviar un mensaje de correo electrnico.
Enviar un mensaje de texto de un telfono celular a otro.
Copiar un archivo a la memoria USB.
Imprimir un documento de Word en el centro de cmputo.
-
268
Use Case Relations.
(extensin) : Los casos de uso pueden
extenderse a otros casos de uso. Se recomienda utilizar
cuando un caso de uso es similar a otro (caractersticas).
-
269
Use Case Relations.
(inclusin) : Los casos de uso pueden incluir a
otros casos de uso. Se recomienda utilizar cuando se tiene
un conjunto de caractersticas que son similares en ms de
un caso de uso y no se desea mantener copiada la
descripcin de la caracterstica.
-
270
Use Case Relations.
Cuando un nmero de casos de uso comparten un
comportamiento comn puede ser descrito por un caso de
uso que es utilizado por otros casos de uso.
-
271
Use Case Relations.
Es una relacin de dependencia donde un caso de uso
extiende otro caso de uso aadiendo acciones a un caso de
uso extendido.
-
272
Example: Use Case Diagrams.
Mquina Recicladora: Sistema que controla una mquina
de reciclamiento de botellas, tarros y jabas. El sistema debe
controlar y/o aceptar:
Registrar el nmero de tems ingresados.
Imprimir un recibo cuando el usuario lo solicita:
Describe lo depositado
El valor de cada item
Total
-
273
Example: Use Case Diagrams.
Existe un operador que desea saber lo siguiente:
Cuantos tems han sido retornados en el da.
Al final de cada da el operador solicita un resumen de todo lo depositado en el da.
El operador debe adems poder cambiar:
Informacin asociada a tems.
Dar una alarma en el caso de que:
Item se atora.
No hay ms papel.
-
274
Example: Use Case Diagrams.
Actores que interactuan con el sistema:
-
275
Example: Use Case Diagrams.
Un Cliente puede depositar Items y un Operador puede
cambiar la informacin de un Item o bien puede Imprimir un
Informe.
-
276
Example: Use Case Diagrams.
Un item puede ser una Botella, un Tarro o una Jaba.
-
277
Example: Use Case Diagrams.
la impresin de comprobantes, que puede ser realizada
despus de depositar algn item por un cliente o bien puede
ser realizada a peticin de un operador.
-
278
Example: Use Case Diagrams.
-
279
Example: Use Case Diagrams.
Sistema de ventas. Un sistema de ventas debe interactuar
con clientes, los cuales efectan pedidos. Adems los clientes
pueden hacer un seguimiento de sus propios pedidos. El
sistema enva los pedidos y las facturas a los clientes. En
algunos casos, segn la urgencia de los clientes, se puede
adelantar parte del pedido (pedidos parciales).
-
280
Example: Use Case Diagrams.
-
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 mximo de tres ejemplares en prstamo de forma simultnea.
Los usuarios pueden solicitar al bibliotecario un libro en prstamo (dando el autor o el ttulo, etc.) y el sistema debe determinar si hay al menos un
ejemplar en las estanteras. Si es as, el bibliotecario entrega un ejemplar
y registra el prstamo (usuario, fecha y ejemplar concreto).
-
282
Exercises: Use Case Diagrams.
El prstamo es semanal y si se produce un retraso en la devolucin, se impone una multa en forma de das sin derecho a nuevos prstamos (3 das
por cada da de retraso).
Antes de cualquier prstamo, el bibliotecario debe comprobar esta situacin.
-
283
Exercises: Use Case Diagrams.
Encontrar los casos de uso para las tareas uno y dos.
-
284
Use Case Diagrams.
-
285
Sequence Diagrams.
Capture the operations of a single use case and show how groups of objects collaborate on those operations.
Exist for each use case.
Contains objects, objects lifelines, messages between objects, conditions, iteration markers, activations, and object deletions.
-
286
Sequence Diagrams.
A Sequence Diagram is an interaction diagram that emphasizes the time ordering of messages.
The diagram show:
The objects participating in the interaction
The sequence of messages exchanged
-
287
Sequence Diagrams.
-
288
Sequence Diagrams.
:Sistema
crearNuevaVenta()
*[ms items]
descripcin, total
:cajero
ingresarItem(codItem, cant)
finalizarVenta()
total con imptos.
realizarPago()
monto cambio, recibo
Bucle
Un diagrama de secuencia del sistema muestra, para un escenario particular de un caso de uso, los eventos externos que los actores generan, su orden y los eventos inter-sistemas.
-
289
Sequence Diagrams.
:JuegodeDados dado1:Dados dado2:Dados
jugar() lanzar()
val1:=getValorMostrado()
lanzar()
val2:=getValorMostrado()
-
290
Sequence Diagrams.
:Computer :PrintServer :Printer
print(arch) print(arch) [no queue]
print(arch)
-
291
Sequence Diagrams.
:Computer :PrintServer :Printer
print(arch) print(arch) [no queue]
print(arch)
Mensaje
Lnea de vida
Activacin
Mensaje Sincrnico
Retorno
Condicin
Objetos participantes en la interaccin
Puede omitirse
-
292
Sequence Diagrams.
:ItemWindow
:Item
NuevoItem(data)
crearItem(data)
Flecha hacia un objeto
ndica creacin del objeto.
:ItemWindow :Item EliminarItem()
BorrarItem() X
X indica destruccin del objeto
-
293
Sequence Diagrams.
Mensaje Simple / Sincrnico No se dan detalles de la comunicacin cuando no
son conocidos o no son relevantes.
Mensaje Asincrnico
Sintaxis del mensaje: Nmero de secuencia [condicin] * [expresin iteracin]
valor de retorno := nombre del mensaje (parmetros)
Respuesta / Resultado
-
294
Sequence Diagrams.
a1:ClaseA b1:ClaseB
u Una ramificacin es mostrada por mltiples mensaje que
abandonan un mismo punto, cada una etiquetada con una
condicin
u Si las condiciones son mutuamente excluyentes representan
condiciones; de otra manera representan concurrencia.
:ClaseC [x>0] Op1()
X
[x
-
295
Sequence Diagrams.
a1:Order b1:OrderLine
Sintaxis: * [expresin-iteacin ] mensaje
*[for each] subtotal()
OrderTotal()
-
296
Sequence Diagrams.
-
297
Sequence Diagrams.
Activation boxes represent the
time an object needs to
complete a task
-
298
Sequence Diagrams.
Messages are arrows that represent
communication between objects.
Use half-arrowed lines to represent
asynchronous messages.
Asynchronous messages are sent
from an object that will not wait for a
response from the receiver before
continuing its tasks.
-
299
Sequence Diagrams.
Lifelines are vertical dashed
lines that indicate the object's
presence over time.
-
300
Sequence Diagrams.
Objects can be terminated
early using an arrow labeled
"< < destroy > >" that points to
an X.
-
301
Sequence Diagrams.
A repetition or loop within a
sequence diagram is depicted
as a rectangle. Place the
condition for exiting the loop at
the bottom left corner in
square brackets [ ].
-
302
Example:
-
303
Example:
-
304
Example:
-
305
Example:
-
306
Example:
-
307
Example:
-
308
Example:
-
309
Example:
-
310
Sequence Diagrams.
Follow these steps to create a sequence diagram. (These are
General guidelines; to write a sequence diagram you must
make sure you check for all interactions among all objects.)
1. Select a use case.
2. Add the first object in the use case to the diagram.
3. Add its method, the message it sends to the next object, and the next
object.
4. Check whether the second object replies to the first or sends on another
message and add the appropriate elements.
-
311
Sequence Diagrams.
5. Repeat steps 3 and 4 as necessary.
6. Add any necessary elements mentioned in this section such
as conditions, iteration markers, or object deletions.
-
312
Sequence Diagrams.
GENERAR EL DIAGRAMA DE SECUENCIA PARA LA
MAQUINA RECICLADORA.
-
313
Collaboration Diagrams.
-
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
-
315
Sequence Diagrams.
-
316
Sequence Diagrams.
-
317
Sequence Diagrams.
-
Arrays
-
319
Group data objects of the same type.
Declare arrays of primitive or class types:
char s[];
Point p[];
char[] s;
Point[] p;
Create space for a reference.
An array is an object; it is
created with new.
Declaring arrays.
-
320
Use the new keyword to create an array object.
For example, a primitive (char) array:
public char[] createArray() {
char[] s;
s = new char[26];
for ( int i=0; i
-
321
Initialize an array element
Create an array with initial values:
String names[];
names = new String[3];
names[0] = "Georgianna";
names[1] = "Jen";
names[2] = "Simon";
String names[] = { "Georgianna","Jen","Simon"};
MyDate dates[];
dates = new MyDate[3];
dates[0] = new MyDate(22, 7, 1964);
dates[1] = new MyDate(1, 1, 2000);
dates[2] = new MyDate(22, 12, 1964);
MyDate dates[] = { new MyDate(22, 7, 1964),new MyDate(1, 1, 2000), new MyDate(22, 12,
1964) };
Initializing Arrays.
-
322
Arrays of arrays:
int twoDim [][] = new int [4][];
twoDim[0] = new int[5];
twoDim[1] = new int[5];
int twoDim [][] = new int [][4]; illegal
Multidimensional Arrays.
-
323
Multidimensional Arrays.
-
324
Multidimensional Arrays.
-
325
Non-rectangular arrays of arrays:
twoDim[0] = new int[2];
twoDim[1] = new int[4];
twoDim[2] = new int[6];
twoDim[3] = new int[8];
Array of four arrays of five integers each:
int twoDim[][] = new int[4][5];
Multidimensional Arrays.
-
326
All array subscripts begin at 0:
int list[] = new int [10];
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
Array Bounds.
-
327
Cannot resize an array
Can use the same reference variable to refer to an entirely new array:
int myArray[] = new int[6];
myArray = new int[10];
Array Resizing.
-
328
The System.arraycopy() method:
Copying arrays
-
329
The System.arraycopy() method:
Copying arrays
-
Class Design
-
331
Subclassing
-
332
Subclassing
-
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:
class [extends ] {
*
}
-
334
Single Inheritance
-
335
Access Control
-
336
Overriding Methods
A subclass can modify behavior inherited from a parent class.
A subclass can create a method with different functionality than the parents method but with the same:
Name
Return type
Argument list
-
337
Overriding Methods
-
338
The Super Keyword
super is used in a class to refer to its superclass.
super is used to refer to the members of superclass,both data attributes and methods.
Behavior invoked does not have
to be in the superclass; it can be
further up in the hierarchy.
-
339
Polymorphism
Polymorphism is the ability to have many different forms; for example, the Manager class has access to methods from Employee class.
An object has only one form.
A reference variable can refer to objects of different forms.
-
340
Virtual Method Invocation
Virtual method invocation:
Employee e = new Manager();
e.getDetails();
Compile-time type and runtime type
-
341
Rules About Overriding Methods
Must have a return type that is identical to the method it overrides
Cannot be less accessible than the method it overrides
-
342
Heterogeneous Collections
Collections of objects with the same class type are called homogenous collections.
MyDate[] dates = new MyDate[2];
dates[0] = new MyDate(22, 12, 1964);
dates[1] = new MyDate(22, 7, 1964);
Collections of objects with different class types are called heterogeneous collections.
Employee [] staff = new Employee[1024];
staff[0] = new Manager();
staff[1] = new Employee();
staff[2] = new Engineer();
-
343
The InstanceOf Operator
-
344
Casting Objects
Use instanceof to test the type of an object
Restore full functionality of an object by casting
Check for proper casting using the following guidelines:
Casts up hierarchy are done implicitly.
Downward casts must be to a subclass and checked by the compiler.
The object type is checked at runtime when runtime errors can occur.
-
345
Overloading method names
Use as follows:
public void println(int i)
public void println(float f)
public void println(String s)
Argument lists must differ.
Return types can be different.
-
346
Overloading Constructors
As with methods, constructors can be overloaded.
Example:
public Employee(String name, double salary, Date DoB)
public Employee(String name, double salary)
public Employee(String name, Date DoB)
Argument lists must differ.
You can use the this reference at the first line of a constructor to call another constructor.
-
347
Overloading Constructors
-
348
The Object Class
The Object class is the root of all classes in Java
A class declaration with no extends clause, implicitly uses extends the Object
public class Employee {
...
}
is equivalent to:
public class Employee extends Object {
...
}
-
349
The == Operator Compared with the equals Method
The == operator determines if two references are identical to each other (that is, refer to the same object).
The equals method determines if objects are equal but not necessarily identical.
The Object implementation of the equals method uses the == operator.
User classes can override the equals method to implement a domain-specific test for equality.
Note: You should override the hashCodemethod if you override the equals method.
-
350
The toString Method
Converts an object to a String.
Used during string concatenation.
Override this method to provide information about a user-defined object in readable format.
Primitive types are converted to a String using the wrapper classs toString static method.
-
351
Wrapper Classes
-
Advanced Class Features
-
353
The Static Keyword
The static keyword is used as a modifier on variables, methods, and nested classes.
The static keyword declares the attribute or method is associated with the class as a whole rather than any particular instance of that class.
Thus static members are often called class members, such as class attributes or class methods.
-
354
Class Attributes
Are shared among all instances of a class
Can be accessed from outside the class without an instance of the class (if marked as public)
-
355
Class Attributes
You can invoke static method without any instance of the class to which it belongs.
-
356
Static Initializers
A class can contain code in a static block that does not exist within a method body.
Static block code executes only once, when the class is loaded.
A static block is usually used to initialize static (class) attributes.
-
357
Abstract Classes
An abstract class models a class of objects where the full implementation is not known but is supplied by the concrete subclasses.
-
358
Interfaces
A public interface is a contract between client code and the class that implements that interface.
AJava interface is a formal declaration of such a contract in which all methods contain no implementation.
Many unrelated classes can implement the same interface.
A class can implement many unrelated interfaces.
Syntax of a Java class:
::=
class [extends ]
[implements [,]* ] {
*
}
-
359
Interfaces
-
360
Java Language Basics
-
361
Unit Objectives
After completing this unit, you should be able to:
Apply the concept of inheritance
Define a subclass and a superclass
Explain overriding methods
Describe the principle of dynamic binding
Explain polymorphism
Define abstract classes and interfaces
-
362
Review.
Classes in Java may have methods and attributes.
Methods define actions that a class can perform.
Attributes describe the class.
-
363
Review.
-
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.
-
365
Review.
-
366
Review.
-
367
Review.
Inheritance - a Fish is Also a Pet
-
368
Review.
-
369
Review.
-
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.
-
371
Inheritance.
-
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.
-
373
Inheritance Hierarchy.
-
374
Inheritance Hierarchy.
-
375
Inheritance Hierarchy.
-
376
Inheritance Hierarchy.
-
377
Inheritance Hierarchy.
Animal
Cat Dog Horse
-
378
Inheritance Hierarchy.
-
379
The Constructor Process.
-
380
Inheritance Hierarchy.
-
381
Inheritance Hierarchy.
-
382
Overriding.
-
383
Polymorphism.
-
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.
-
385
Dynamic Binding and Polymorphism.
-
386
Dynamic Binding and Polymorphism.
-
387
Dynamic Binding and Polymorphism.
-
388
Dynamic Binding and Polymorphism.
-
389
Upcast/Downcast.
-
390
Abstract Classes.
-
391
Abstract Classes.
-
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).
-
393
Interfaces.
-
394
Interfaces.
-
395
Interfaces.
-
Exceptions and Exceptions Handling
-
397
An exception is an event or condition that disrupts the normal flow of execution in a program
Exceptions are errors in a Java program
The condition causes the system to throw an exception
The flow of control is interrupted and a handler will catch the exception
Exception handling is object-oriented
It encapsulates unexpected conditions in an object
It provides an elegant way to make programs robust
It isolates abnormal from regular flow of control
Exceptions.
-
398
A JVM can detect unrecoverable conditions
Examples:
Class cannot be loaded
Null object reference used
Both core classes and code that you write can throw exceptions
Examples:
IO error
Divide by zero
Data validation
Business logic exception
Exceptions terminate
execution unless they
are handled by the
program
Exceptions.
-
399
Throwable is the base class, and provides a common interface and implementation for most exceptions
Error indicates serious problems that a reasonable application should not try to catch, such as:
VirtualMachineError
CoderMalfunctionError
Exception heads the class of conditions that should usually be either caught or specified as thrown
A RuntimeException can be thrown during the normal operation of the JVM
Methods may choose to catch these but need not specify them as thrown
Examples:
ArithmeticException
BufferOverflowException
The Exceptions Hierarchy
-
400
The Exceptions Hierarchy
-
401
Checked exceptions must be either handled in the method where they are generated, or delegated to the calling method
Handling Exceptions
-
402
throws
A clause in a method declaration that lists exceptions that may be delegated up the call stack
Example: public int doIt() throws SomeException,
try
Precedes a block of code with attached exception handlers
Exceptions in the try block are handled by the exception handlers
catch
A block of code to handle a specific exception
finally
An optional block which follows catch clauses
Always executed regardless of whether an exception occurs
throw
Launches the exception mechanism explicitly
Example: throw (SomeException)
Keywords
-
403
To program exception handling, you must use try/catch blocks
Code that might produce a given error is enclosed in a try block
The catch clause must immediately follow the try block
try/catch blocks
-
404
The clause always has one argument that declares the type of exception to be caught
The argument must be an object reference for the class Throwable or one of its subclasses
Several catch clauses may follow one try block
The catch clause
-
405
Example
-
406
Example
-
407
Optional clause that allows cleanup and other operations to occur whether an exception occurs or not
May have try/finally with no catch clauses
Executed after any of the following:
try block completes normally
catch clause executes
Even if catch clause includes return
Unhandled exception is thrown, but before execution returns to calling method
The finally clause
-
408
Example
-
409
It may be necessary to handle exceptions inside a catch or finally clause
For example, you may want to log errors to a file, but all I/O operations require IOException to be caught.
Do this by nesting a try/catch (and optional finally) sequence inside your handler
Nested Exception Handling
-
410
Not to be confused with keyword throws
Can be used in a try block when you want to deliberately throw an exception
You can throw a predefined Throwable object or your own Exception subtype
Create a new instance of the exception class to encapsulate the condition
The flow of the execution stops immediately after the throw statement, and the next statement is not reached
A finally clause will still be executed if present
The throw keyword
-
411
What happens when something goes wrong in the JVM?
It throws an error derived from Error depending on the type of problem
What happens if RuntimeException is thrown?
Methods are not forced to declare RuntimeException in their throws clauses; the exception is passed to the JVM
The JVM does the necessary cleaning and terminates the application or applet
Handling runtime exceptions
-
412
An assertion is a Java statement that allows you to test your assumptions about your program
In a traffic simulator, you might want to assert that a speed is positive, yet less than a certain maximum
An assertion contains a boolean expression that you believe will be true when the assertion executes if not true, the system throws an error
By verifying that the boolean expression is true, the assertion confirms your assumptions about the behavior of your program, increasing your
confidence that the program is free of errors
Benefits:
Writing assertions while programming is a quick and effective way to detect and correct bugs
Assertions document the inner workings of your program, enhancing maintainability
Assertions
-
413
Two forms:
assert ;
assert : ;
If the boolean expression is false:
Form 1 throws an AssertionError with no message
Form 2 throws an AssertionError with a message defined by evaluating the second expression
Assertion checking is disabled by default.
Must be enabled at Java command line using the enableassertions switch
Assertions can be enabled or disabled on a package-bypackage or class-by-class basis
assert statements are ignored if not enabled
Using assertions
-
414
Do not use assertions:
For argument checking in public methods
To do any work that your application requires for correct operation
Use assertions to test:
Internal invariants (values that should not change)
For example, place default: assert false at the end of switch statements with no default
Control-flow invariants
For example, place assert false at locations that should never be reached
Preconditions, postconditions, and class invariants
For example, argument checking in private methods
When to use assertions
-
415
Do not use assertions:
For argument checking in public methods
To do any work that your application requires for correct operation
Use assertions to test:
Internal invariants (values that should not change)
For example, place default: assert false at the end of switch statements with no default
Control-flow invariants
For example, place assert false at locations that should never be reached
Preconditions, postconditions, and class invariants
For example, argument checking in private methods
When to use assertions
-
Building Java Guis
-
417
Abstract Window Toolkit (AWT).
Provides graphical user interface (GUI) components that are used in all Java applets and applications.
Contains classes that can be composed or extended. Classes can also be abstract.
Ensured that every GUI component that is displayed on the screen is a subclass of the abstract class Component or MenuComponent.
Has Container, which is an abstract subclass of Component and includes two subclases:
Panel
Window
-
418
Abstract Window Toolkit (AWT).
-
419
Containers.
Add components with the add methods.
The two main types of containers are Window and Panel.
A Windows is a free floating window on the display.
A Panel is a container of GUI components that must exists in the context of some other container, such as a window or applet.
-
420
Containers.
-
421
The Component class.
The Component class defines the attributes and behavior common to all visual components used in the user interface. It is an abstract class. It also defines
the way in which applications and applets can interact with users by capturing
events.
-
422
Frames.
Are a subclass of Window
Have title and resizing corners
Are initially invisible, use setVisible(true) to expose the frame
Have BorderLayout as the default layout manager
Use the setLayout method to change the default layout manager.
Frame inherits its characteristics from the Container class so you can add
Components to a frame using the add method.
-
423
Frames.
-
424
Frames.
-
425
Frames.
-
426
Frames.
-
427
Frames.
-
428
Frames.
-
429
The Panel Class.
The Panel class is a container on which components can be
placed.
After you create a Panel, you must add it to a Window or
Frame. This is done using the add method of the Container
class. Then set the frame to be visible so that the frame and
panel are displayed.
-
430
The Panel Class.
-
431
The Panel Class.
-
432
Containers Layouts.
FlowLayout
top related