Transcript Lecture 3

Slide #1
Object Oriented Design
• In this lecture, we will introduce the basic notions of
object oriented design
• We will examine some classes in the Java API and how
they can be used
• In the next lecture, we will learn how objects are defined
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #2
Program Development
• The creation of software involves four basic activities:
–
–
–
–
establishing the requirements
creating a design
implementing the code
testing the implementation
• The development process is much more involved that
this, but these basic steps are a good starting point
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #3
Requirements
• Requirements specify the tasks a program must
accomplish (what to do, not how to do it)
• They often address the user interface
• An initial set of requirements are often provided, but
usually must be critiqued, modified, and expanded
• It is often difficult to establish detailed, unambiguous,
complete requirements
• Careful attention to the requirements can save significant
time and money in the overall project
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #4
Design
• A program follows an algorithm, which is a step-by-step
process for solving a problem
• The design specifies the algorithms and data needed
• The details of a specific algorithm may be expressed in
pseudocode, which is code-like, but does not necessarily
follow any specific syntax
• example: compute average:
– read numbers from user
– for each number:
• add to a sum variable, increment counter
– output sum / counter
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #5
Implementation
• Implementation is the process of translating a design into
source code
• Most novice programmers think that writing code is the
heart of software development, but it actually should be
the least creative
• Almost all important decisions are made during
requirements analysis and design
• Implementation should focus on coding details, including
style guidelines and documentation
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #6
Testing
• A program should be executed multiple times with
various input in an attempt to find errors
• Debugging is the process of discovering the cause of a
problem and fixing it
• Programmers often erroneously think that there is "only
one more bug" to fix
• Tests should focus on design details as well as overall
requirements
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #7
The Waterfall Model
Requirements
Design
Implementation
Testing
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #8
Introduction to Object-Oriented Design
• The real world consists of object: students, houses, cars...
• As human beings, we like to classify these objects and
characterize them:
–
–
–
–
Dogs bark and like to eat bonzo
In general, politicians do not tell the truth
Triangles have three edges and sum of degrees 180
Cars have gas and brake pedals, gear shift stick, steering wheel,
... If the gears are in reverse and you press the gas pedal, the car
drives back.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #9
From Real-World objects to Software Objects
• As in the real world, the design of sofwtare also involves
processes such as identifying new classifications and
characterizing them
– A bank client has a credit profile which should have information
on his personal earnings, real estate assets, savings etc.
– A credit profile should be updated monthly and must have an
estimation method
• These new classifications also define objects, but this
time they are software objects
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #10
Software Objects
• Just as the real world has objects, it is very useful to
think of a software program as made of objects.
• The objects in a software program are units which
perform predefined tasks.
• These units interact with eachother in a special manner,
and this way the task can be accomplished.
• A simple example:
Program
Display Text
“Hello World”
The Interdisciplinary Center, Herzelia
OutputWindow
Lecture 3, Introduction to CS - Information Technologies
Slide #11
Real World vs. Software Objects
• Sometimes software object model real world objects
(bank account, client, form...) and sometimes other weird
things (Logo turtle, output window, unix to unicode
adaptor)
• Note that real world objects do not necessarily represent
tangible objects - they can refer to abstract notions
(client profile)
• As for software objects - they may sometimes represent
tangible objects, but they generally do not
• In general, software objects have a strong connection to
real-world objects, and it’s helpful to think of them this
way
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #12
State and Behaviour
• Software objects are characterized by two important
things:
– State: The object’s attributes
– Behaviour: What the object can do, or what can be
done with the object, and how the objects reacts
• Examples:
– A LOGO turtle has a location, current angle, the state of it tail
(up/down). It can move forwards, move backwards, turn left,
turn right, etc.
– An Output Window has a location, size and a text it displays.
One can append new text to the window, clear it, move it, resize
it, close it, etc.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #13
State and Behaviour
• The state of a software object is held in internal
variables, or fields.
• The behaviour of an object is represented by methods which define the functionality of the object (what it can
do, or what can be done with it):
– moveForward(double units)
– turnLeft(int degrees)
– tailDown()
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #14
Classes of Objects
•
•
•
•
All cars in the world have similar attributes
(color, model, production year, license id, pedals,
gear shift stick, etc...) and behaviour (driving)
Each car of many different cars can be identified
by its own set of attributes
However, all cars are driven in the same way
(more or less)
We say that there is a class of cars in the world,
and each car is an object in this class, or: each
car object is an instance (‫)מופע‬of the class car.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #15
Car Object
Class Car
Color
Model
Prodution year
...
accelerate(int rate)
brake()
turnRight()
turnLeft()
changeGears()
...
The Interdisciplinary Center, Herzelia
Color = black
Model = ford
Prodution year = 1932
...
accelerate(int rate)
brake()
turnRight()
turnLeft()
changeGears()
...
Car Object
Color = red
Model = suzuki
Prodution year = 1997
...
accelerate(int rate)
brake()
turnRight()
turnLeft()
changeGears()
...
Car Object
Color = off white
Model = susita
Prodution year = 1970
...
accelerate(int rate)
brake()
turnRight()
turnLeft()
changeGears()
...
Lecture 3, Introduction to CS - Information Technologies
Slide #16
... And in Software
•
•
•
•
•
A class is a description of objects having the same
attributes and methods.
It can be thought of a blueprint (‫ )תבנית‬for the object
A class defines the methods and state variables
associated with an object
There can be many different objects of the same class,
each having its own attributes. However, all objects
conform to the same set of methods.
Example: you can open as many Output Windows as you
want. But displaying text on all of them is done in the
same manner.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #17
Instantiation & Initialization
•
•
•
•
The creation of a new object involves two
things: creating an empty object and initializing
its state.
Objects are always initialized when they are
created. So the state of the object is always
defined.
The creation of some objects requires
information specifying their initial state. Other
require no such information.
Example: A LOGO Turtle does not require any
information for its creation. We will see other
objects that require information later.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #18
Creating New Objects
•
We use the operator new to create objects:
new Turtle();
new InputRequestor();
new Student(“Jimi”,”Biology”,2);
•
The operator new is followed by the name of the
class from which we want to create a new
instance, followed by a pair of parenthesis. If the
creation requires parameters, we write them
inside the parenthesis.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #19
References
•
•
•
•
•
Objects live in the main memory.
When an object is created it is allocated a block of
memory sufficient to hold all its state variables. The
object occupies this block until it is destroyed.
We have no control on the location in memory, where an
object is created. It is just created somewhere.
In order to interact with an object, we must have some
way to refer to it.
We refer to an object by means of an object reference.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #20
References
•
•
An object reference is a special kind of value that
identifies an object.
Object references can be stored in variables.
Turtle leonardo = new Turtle();
Student jimi =
new Student(“Jimi”,”Biology”,2);
•
The variable hold the reference to a particular object. It
refers to this object. We can interact with the object
through a variable that refers to it.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #21
References
•
•
The declaration of the object reference variable
and the creation of the object can be separate
activities.
We declare a variable named leonardo whose
type is ‘a reference to Turtle’:
Turtle leonardo;
•
leonardo can store a reference to an instance
of class Turtle. However, no Turtle object is
created yet and the value of leonardo is
undefined!
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #22
References
•
•
•
We now create a new Turtle object and store the
reference to it in the variable leonardo:
leonardo = new Turtle();
In a later stage of the program, leonardo can be set to
refer to another object, but it can only refer to a Turtle
object.
There is a special null value that can be assigned to any
reference variable to denote that this variable does not
refer (currently) to any object.
leonardo = null;
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #23
Methods
•
We interact with an object by means of method
invocation:
Turtle leonardo = new Turtle();
leonardo.turnLeft(90);
leonardo.moveForwards(100);
• Some methods have return values:
InputReader in = new InputReader();
int x = in.readInt
(“Please enter a number”);
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #24
References
• An object reference holds the memory address of an
object
ChessPiece bishop1 = new ChessPiece(“black”);
bishop1
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #25
References
ChessPiece bishop1 =
new ChessPiece(“black”);
ChessPiece bishop2 =
new ChessPiece(“white”);
The Interdisciplinary Center, Herzelia
bishop2
bishop1
Lecture 3, Introduction to CS - Information Technologies
Slide #26
Reference Assignment
• For object references, the value of the memory location
is copied:
bishop2 = bishop1;
Before
bishop1
bishop2
The Interdisciplinary Center, Herzelia
After
bishop1
bishop2
Lecture 3, Introduction to CS - Information Technologies
Slide #27
Reference Assignment
bishop2
bishop1
bishop2 = bishop1;
System.out.println
(bishop2.getColor());
// prints “black”
b u c k e t 1
b u c k e t 2
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #28
Assignment of Primitive Types
• The act of assignment takes a copy of a value and stores
it in a variable
• For primitive types:
num2 = num1;
Before
After
num1
num2
num1
num2
5
12
5
5
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #29
Aliases
• Two or more references that refer to the same object are
called aliases of each other
• There is only one copy of the object (and its data), but
with multiple ways to access it
• Aliases can be useful, but should be managed carefully
• Affecting the object through one reference affects it for
all aliases, because they refer to the same object
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #30
Garbage Collection
• When an object no longer has any valid references to it,
it can no longer be accessed by the program
• It is useless, and therefore called garbage
• Java performs automatic garbage collection periodically,
returning an object's memory to the system for future use
• In other languages, the programmer has the
responsibility for performing garbage collection
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #31
Class Libraries
• The Java API is a class library, a group of classes that
support program development, and offer a wide variety
of services
• The Java API is separated into packages
• Each package contains a set of classes that relate in some
way
• The System class, for example, is in package
java.lang
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #32
The Java API Packages
• Some packages in the Java API:
java.applet
java.awt
java.beans
java.io
java.lang
java.math
The Interdisciplinary Center, Herzelia
java.net
java.rmi
java.security
java.sql
java.text
java.util
Lecture 3, Introduction to CS - Information Technologies
Slide #33
Importing Packages
• Using a class from the Java API can be accomplished by
using its fully qualified name:
java.lang.System.out.println();
• Or, the package can be imported using an import
statement, which has two forms:
import java.applet.*;
import java.util.Random;
• The java.lang package is automatically imported
into every Java program
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #34
Example: The String Class
•
A character string in Java is an object, defined by
the String class
String name =
new String ("Ken Arnold");
•
Because strings are so common, Java allows an
abbreviated syntax:
String name = "Ken Arnold";
•
Once a String object is created, it cannot change
its value. Strings are immutable objects.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #35
Some Useful Methods in String
• charAt(int index)
• indexOf(char ch)
• lastIndexOf(char ch)
• startsWith(String suffix)
• lastIndexOf(char ch)
• length()
• ...See the API!
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #36
String sentence =
“Houston, we have a problem.”;
int length = sentence.length(); // length=27
String word = sentence.substring(0,7);
// word = “Houston”
word = word.toLowerCase();
// word = “houston”;
char c = word.charAt(2); // c=‘u’
boolean b = word.equals(“Houston”); // b=false
int index = sentence.indexOf(“we”);
word = sentence.substring(index, index+3);
// word=“we “
word = word.trim(); // word=“we”
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #37
class StringTest {
public static void main (String[] args) {
String
String
String
String
String
String
str1
str2
str3
str4
str5
str6
=
=
=
=
=
=
"Seize the day";
new String();
new String (str1);
"Day of the seize";
"Seize the day";
new String(“Seize the day”);
System.out.println ("str1:
System.out.println ("str2:
System.out.println ("str3:
System.out.println ("str4:
System.out.println ("str5:
System.out.println();
The Interdisciplinary Center, Herzelia
"
"
"
"
"
+
+
+
+
+
str1);
str2);
str3);
str4);
str5);
Lecture 3, Introduction to CS - Information Technologies
Slide #38
System.out.println ("Length of str1: " + str1.length());
System.out.println ("Length of str2: " + str2.length());
System.out.println();
System.out.println ("Index of 'e' in str4: " +
str4.indexOf('e'));
System.out.println ("Last index of 'e' in str4: " +
str4.lastIndexOf('e'));
System.out.println ("The character at position 3 in str1: " +
str1.charAt(3));
System.out.println ("The substring of str1 from " +
"position 6 to position 8: " + str1.substring(6, 9));
System.out.println();
if (str1 == str5)
System.out.println ("str1 and str5 refer " +
"to the same object.");
if (str1 != str3)
System.out.println ("str1 and str3 do NOT refer " +
"to the same object.");
if (str1.equals(str3))
System.out.println ("str1 and str3 contain the same “ +
“characters.");
System.out.println();
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #39
str2 = str1.toUpperCase();
System.out.println ("str2 now refers to: " + str2);
if (str1.equalsIgnoreCase(str2))
System.out.println ("str1 and str2 contain the same " +
"characters (ignoring case).");
str5 = str1.replace('e', 'X');
System.out.println ("str5 now refers to: " + str5);
System.out.println();
System.out.println ("str1 starts with \"Seize\": " +
str1.startsWith("Seize"));
System.out.println ("Creating a string from a number: " +
String.valueOf(22+33+44));
} // method main
} // class Carpe_Diem
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #40
The Output
str1:
str2:
str3:
str4:
str5:
Seize the day
Seize the day
Day of the seize
Seize the day
Length of str1: 13
Length of str2: 0
Index of ‘e’ in str4: 9
Last index of ‘e’ in str4: 15
The character at position 3 in str1: z
The substring of str1 from position 6 to position 8: the
str1 and str5 refer to the same object
str1 and str3 do NOT refer to the same object
str1 and str3 contain the same characters
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #41
The Output (cont).
str2 now refers to: SEIZE THE DAY
str1 and str2 contain the same characters (ignoring case)
str5 now refers to SXizX thX day
str1 starts with “Sieze”: true
Creating a string from a number: 99
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #42
The String Lesson
• We do not need to know the implementation of an object
to use it - we only need the interface
• The interface and the implementation are defined by a
class
• Many instances - objects - of the same class can be
created
• These instances differ by their state
• It is possible to have two different instances of the same
class with the same state
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #43
The String Lesson (cont.)
• Just as in primitive data types, an object must be
initialized
• There could be several ways to initialize an object
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #44
Yet Another Example - The Random class
• The need to use random numbers occurs frequently in
software (simulations, games, ...)
• Real random numbers cannot be generated on a computer
• A pseudo-random number generator:
– pick a random seed
– first number is a function of the seed
– each number is a function of the last
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #45
The Random Class
• Defined in the java.util package
• Implements a pseudo-random number generator
• Useful methods:
– nextInt() - random integer across the entire int spectrum
– nextFloat() - a random float between 0 and 1
• Dice:
Random dice = new Random();
int roll = Math.abs(dice.nextInt()) % 6 + 1;
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #46
The Random Class
Expression
Range
Math.abs (rand.newInt()) % 6 + 1
1 to 6
Math.abs (rand.newInt()) % 10 + 1
1 to 10
Math.abs (rand.newInt()) % 101
0 to 100
Math.abs (rand.newInt()) % 11 + 20
20 to 30
Math.abs (rand.newInt()) % 11 - 5
-5 to 5
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #47
import java.util.*;
class Flip {
public static void main (String[] args) {
Random coin = new Random();
int count = 0, heads = 0, tails = 0;
int number_flips, flip_result;
InputReader in = new InputReader();
OutputWindow out = new OutputWindow();
in.readInt(“Please enter the number of flips”);
while (count < number_flips) {
flip_result = Math.abs (coin.nextInt()) % 2;
if (flip_result == 0)
heads = heads + 1;
else
tails = tails + 1;
count = count + 1;
}
out.println ("heads = " + heads + “ tails = “ + tails);
} // method main
} // class Flip
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #48
The StringBuffer Class
• String class manages the use of immutable strings, i.e.,
they cannot change their size or content
• The StringBuffer class allows to use dynamic
strings - which can be modified
–
–
–
–
–
–
append(char c)
insert(int index, char c)
charAt(int index)
setCharAt(int index, char c)
reverse()
length()
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #49
class StringBufferTest {
public static void main
StringBuffer text1 =
StringBuffer text2 =
StringBuffer text3 =
(String[] args) {
new StringBuffer();
new StringBuffer(“ m”);
new StringBuffer(“1 dollar”);
text1.append(1);
text1.append(“ p”);
text1.append(‘e’);
text1.append(‘n’);
text1.append(“ny”);
text2.insert(0,1);
text2.insert(2,”di”);
text2.insert(5,’e’);
System.out.println(text1);
System.out.println(text2);
System.out.println(text3);
text3.reverse();
System.out.println(text3);
}
}
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #50
Output:
1 penny
1 dime
1 dollar
rallod 1
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #51
The StringTokenizer Class
• Characters in a string can be grouped into meaningful pieces
– e.g., characters in a sentence can be grouped into words
• The StringTokenizer class enables to break a string into
pieces, called tokens, based on a set of delimiters.
• By default, delimiters are space, tab, CR, and newline (white space)
• Two useful methods in StringTokenizer:
– countTokens() - returns the number of tokens left in the
string
– nextToken() - returns the next token in the string
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #52
StringTokenizer reader = new StringTokenizer
(“Que sera sera, whatever will be will be”);
String str;
Que sera sera, whatever will
be will be
reader
str
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #53
str = reader.nextToken();
Que sera sera, whatever will
be will be
nextToken()
reader
str
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #54
String str = reader.nextToken();
sera sera, whatever will
be will be
reader
str
The Interdisciplinary Center, Herzelia
Que
Lecture 3, Introduction to CS - Information Technologies
Slide #55
String str = reader.nextToken();
sera sera, whatever will
be will be
reader
str
The Interdisciplinary Center, Herzelia
Que
Lecture 3, Introduction to CS - Information Technologies
Slide #56
int n = reader.countTokens();
sera sera, whatever will
be will be
countTokens()
reader
str
The Interdisciplinary Center, Herzelia
Que
Lecture 3, Introduction to CS - Information Technologies
Slide #57
int n = reader.countTokens();
sera sera, whatever will
be will be
7
reader
str
The Interdisciplinary Center, Herzelia
Que
n
Lecture 3, Introduction to CS - Information Technologies
Slide #58
str = reader.nextToken();
sera sera, whatever will
be will be
nextToken()
reader
str
The Interdisciplinary Center, Herzelia
Que
Lecture 3, Introduction to CS - Information Technologies
Slide #59
str = reader.nextToken();
sera, whatever will
be will be
sera
reader
str
The Interdisciplinary Center, Herzelia
Que
Lecture 3, Introduction to CS - Information Technologies
Slide #60
str = reader.nextToken();
sera, whatever will
be will be
sera
reader
str
The Interdisciplinary Center, Herzelia
Que
Lecture 3, Introduction to CS - Information Technologies
Slide #61
str = reader.nextToken();
sera, whatever will
be will be
sera
reader
str
The Interdisciplinary Center, Herzelia
Que
Lecture 3, Introduction to CS - Information Technologies
Slide #62
str = reader.nextToken();
sera, whatever will
be will be
sera
reader
str
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #63
String str1 = reader.nextToken();
sera, whatever will
be will be
nextToken()
reader
sera
str
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #64
String str1 = reader.nextToken();
sera,
whatever will
be will be
sera
reader
str
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #65
String str1 = reader.nextToken();
str1
sera,
whatever will
be will be
sera
reader
str
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #66
import java.util.StringTokenizer;
class BreakSentence {
public static void main(String[] args) {
InputReader in = new InputReader();
OutputWindow out = new OutputWindow();
StringTokenizer reader;
String str = in.readString("Please enter a sentence");
reader = new StringTokenizer(str);
out.println(reader.countTokens());
while (reader.countTokens() > 0) {
out.println(reader.nextToken());
out.println(reader.countTokens());
}
}
}
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #67
input:
Hello, my name is Gadi.
output:
5
Hello,
4
my
3
name
2
is
1
Gadi.
0
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #68
Encapsulation
•
•
•
An interface to an object is how it should be
operated
An implementation of an object is how the object
is built and how it works
In a software object:
– interface: the set of methods which is defined on the
object
– implementation: how the object’s state is represented
(the state variables) and how the object’s method
change its state
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #69
Hiding the Implementation
•
•
Objects should generally hide their
implementation
This servers two purposes:
• allows us to use the objects easily
• allows us to change the object’s implementation later
without effecting how it is used.
• Good exmpales: Car, Turtle
• Bad examples: Typewriter, year 2000 bug,
Patriot example
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #70
Black Boxes
•
An encapsulated object can be thought of as a
black box; its inner workings are hidden from
the client
a Turtle object
moveForward()
tailUp()
client
turnLeft()
turnRight()
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #71
Encapsulation
public
API
The Interdisciplinary Center, Herzelia
private
implementation
details
Lecture 3, Introduction to CS - Information Technologies
Slide #72
Encapsulation - Why?
•
•
•
•
From the external view, an object is an
encapsulated entity, providing a set of specific
services
These services define the interface to the object
The user, or client, of an object can request its
services, but it should not have to be aware of
how those services are accomplished
Encapsulation makes an object easy to manage
mentally because its interaction with clients is
limited to a set of well-defined services
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #73
What Should be Encapsulated?
• A real world example: 220/110 switch in an
electric unit.
• Another example: manual/automatic
transmission in a car
• An object has complete control over what is
exposed and what isn’t: this is stated in the class
defining the object
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #74
Abstraction
• Abstraction is the process of classification and
characterization of new objects
•
•
We think of the object in its ideal form. What
does it represent? What behaviors it should
have?
Objects usually interact with other objects to
achieve their role.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #75
Design of Complex Systems
• When designing a complex system, we divide
the system into several autonomous components
(objects).
• Each has a well defined role and interface. These
objects interact between them to achieve the
functionality of the whole system.
• The components themselves can be further
divided into smaller components.
• This process is sometimes called “top down
design”
• Example: Stereo System
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #76
Modularity
•
•
A good characteristic of a system is its modularity - the
ease of plugging and replacement of the units (objects)
which comprise the system
Building our system from smaller components, has
several advantages:
• It is easier to understand the systems in terms of a
collection of few interoperating object.
• We can correct/improve the implementation of one
component, without effecting the others.
• A component may be used later in other places. We
may find components written by others that are
suitable for our needs.
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies
Slide #77
Guidelines for Designing Reusable Objects
• Autonomous - an object should be an autonomous
entity, so it could work anywhere.
• Good abstraction - an object should have a good
abstraction, so others can easily understand its behaviour
• Clear interface - an object should have a clear interface,
so it will be easy to work with, and to maintain.
– An interface to the object includes good method documentation
and good method and class naming. This is essential: otherwise,
no one can understand how to use the object
The Interdisciplinary Center, Herzelia
Lecture 3, Introduction to CS - Information Technologies