View
290
Download
5
Embed Size (px)
Citation preview
Objects and ClassesObjects and Classes
• objects
• defining classes
• method declaration
• object references and aliases
• instance variables
• encapsulation and visibility modifiers
basic programming
concepts
object oriented programming
topics in computer science
syllabus
2unit 4
Principles of object-oriented programmingPrinciples of object-oriented programming
encapsulation: data is protected from “external” users
inheritance: properties and methods defined for a certain structures can be used by all structures defined as direct offspring
polymorphism: the same function call may invoke different code, depending on context
3unit 4
What are objects?What are objects?
We divide the system into several autonomous components (objects), each has a well defined role and interface. These objects interact to achieve the functionality of the whole system.
The components themselves can be further divided into smaller components (e.g., stereo system)
The use of objects eases the design and maintenance of complex systems.
4unit 4
Advantages of modular systems:Advantages of modular systems:
Readability: system is easier to understand
Independence: we can change the implementation of one component, without affecting the others
Reusability: a component may be used later in other places; or, we may find components written by others that are suitable for our needs
5unit 4
Modularity & ReusabilityModularity & Reusability
In order for our components to be reusable we should design them as:• Autonomous - a component should be an
autonomous entity, so it could work anywhere
• Abstraction - it should have a clear abstraction, so others can easily understand it’s behavior (know what to expect from it)
• Clear interface - it should have a clear interface so it will be easy to work with, and to maintain
• Documentation & Naming - without documentation and good naming for interface methods, no one will understand how to use it
6unit 4
ObjectsObjects
An object is characterized by its:• State -- attributes (descriptive characteristics)
• BehaviorsBehaviors -- what it can do (or be done to it)
For example, consider an object “checking account”:• The state of the account is the amount of money in it
• The behaviors of the account include money deposit and withdrawal
• The behavior of the account typically changes its state
7unit 4
ClassesClasses
A class is a description of objects having the same attributes and behaviors:• It is the model or pattern from which objects are created
• It can be thought of as a blueprint for the object
A class defines the characteristics associated with an object:• state -- internal variables
• behaviors -- methods
8unit 4
Example – the Coin classExample – the Coin class
coin is an object which contains one piece of data, the state variable face
behaviors are missing: what can we do to, and with, a coin?
public class Coin{ public final int HEADS = 0; public final int TAILS = 1; private int face;}
9unit 4
ClassesClasses
A class contains data declarations and method declarations
int face;char ch;
Data declaration (state variables)Data declaration (state variables)
Method declaration (behavior)Method declaration (behavior)
10unit 4
Writing MethodsWriting Methods
object behavior list of methods
A method declaration specifies the code that will be executed when the method is invoked (or called)
11unit 4
Example: the Coin ClassExample: the Coin Class
In the Coin class we could define the following data:• face, an integer that represents the current face• HEADS and TAILS, integer constants that represent the
two possible states
We might also define the following methods:• a flip method, to flip the coin
• a getFace method, to return the current face
public class Coin}
public final int HEADS = 0; public final int TAILS = 1;
private int face;-----------------------------------------------------------------//
// Flips the coin by randomly choosing a face-----------------------------------------------------------------//
public void flip() }
face = (int) (Math.random() * 2);{ -----------------------------------------------------------------//
// Returns the current face of the coin as an integer-----------------------------------------------------------------//
public int getFace} () return face;
{ {
13unit 4
Using objectsUsing objects
Object are defined and use by other parts of the program
The application program is also an object
public class CountFlips }-----------------------------------------------------------------//
// Flips a coin multiple times and counts the number of heads // and tails that result.
-----------------------------------------------------------------// public static void main (String[] args)}
final int NUM_FLIPS = 1000; int heads = 0, tails = 0;
Coin myCoin = new Coin(); // instantiate the Coin object for (int count=1; count <= NUM_FLIPS; count++)
} myCoin.flip;()
if (myCoin.getFace() == myCoin.HEADS) heads;++ else tails;++
{ System.out.println ("The number flips: " + NUM_FLIPS);
System.out.println ("The number of heads: " + heads); System.out.println ("The number of tails: " + tails);
{ {
15unit 4
Expanding the Coin ClassExpanding the Coin Class
Once the Coin class has been defined, we can use it again in other programs as needed
We can add methods and variables as needed; “old” application programs will still work; a program will not necessarily use every service provided by an object
For example, we will add the following methods:• a Coin constructor, to set up the object
• a toString method, to return a string description for printing
public class Coin}
public final int HEADS = 0; public final int TAILS = 1;
private int face;-----------------------------------------------------------------//
// Constructor: sets up the coin by flipping it initially-----------------------------------------------------------------//
public Coin() }
flip;(){
-----------------------------------------------------------------// // Flips the coin by randomly choosing a face
-----------------------------------------------------------------// public void flip()
} face = (int) (Math.random() * 2);
{
-----------------------------------------------------------------// // Returns the current face of the coin as a string
-----------------------------------------------------------------// public String toString}()
String faceName;
if (face == HEADS) faceName = "Heads;"
else faceName = "Tails;"
return faceName;{
-----------------------------------------------------------------// // Returns the current face of the coin as an integer
-----------------------------------------------------------------// public int getFace} ()
System.out.print(toString()); return face;
{ {
18unit 4
Writing MethodsWriting Methods
When a method is invoked, the flow of control jumps to the method and executes its code
When complete, the flow returns to the place where the method was called and continues
The invocation may or may not return a value, depending on how the method was defined
19unit 4
flip;()
flip()Coin
Method Control FlowMethod Control Flow
The called method could be within the same class, in which case only the method name is needed
20unit 4
getFace
toString
toString;()
myCoin.getFace;()
CountFlips.main
Method Control FlowMethod Control Flow
The called method could be part of another class or object
21unit 4
Instance DataInstance Data
The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own
A class declares the type of the data, but it does not reserve any memory space for it
Every time a Coin object is created, a new face variable is created as well
The objects of a class share the method definitions, but they have unique data space
22unit 4
Instance DataInstance Data
face 0
coin1
flip()
getFace()
toString()
int face;
class Coin
face 1
coin2
23unit 4
Classes and ObjectsClasses and Objects
There can be many different objects of a single class
class Coin
face
flip()
getFace()
...
HEAD
flip()
getFace()...
TAIL
flip()
getFace()...
TAIL
flip()
getFace()...
Coin objects
24unit 4
Data ScopeData Scope
The scope of data is the area in a program in which that data can be used (referenced)
Data declared at the class level can be used by all methods in that class
Data declared within a method can only be used in that method
Data declared within a method is called local data
Example: Coin.face
25unit 4
Creating ObjectsCreating Objects
The creation of a new object involves two things: 1. creating an empty object 2. initializing its state
Objects are always initialized when they are created the state of the object is always defined by automatically activating the constructor method
The creation of some objects requires information specifying their initial state; for example, to create a new Coin we provide no additional information, the face is chosen randomly (via flip)
26unit 4
Creating ObjectsCreating Objects
We use the operator new to create objects: new Coin();
new ChessPiece(“bishop”,”b”,1);
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.
public class FlipRace } public static void main (String[] args) { final int GOAL = 3; int count1 = 0, count2 = 0; // Create two separate coin objects Coin coin1 = new Coin(); Coin coin2 = new Coin(); while (count1 < GOAL && count2 < GOAL) { coin1.flip(); coin2.flip();
// Print the flip results (uses Coin's toString method) System.out.print ("Coin 1: " + coin1); System.out.println (" Coin 2: " + coin2);
// Increment or reset the counters count1 = (coin1.getFace() == coin1.HEADS) ? count1+1 : 0; count2 = (coin2.getFace() == coin2.HEADS) ? count2+1 : 0; }
// Determine the winner if (count1 < GOAL) System.out.println ("Coin 2 Wins!"); else if (count2 < GOAL) System.out.println ("Coin 1 Wins!"); else System.out.println ("It's a TIE!"); }}
29unit 4
ReferencesReferences
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.
30unit 4
Object referencesObject references
An object reference is a special kind of value that identifies an object
Object references can be stored in variables: Coin myCoin = new Coin(); ChessPiece bishop1 =
new ChessPiece(“bishop”,”b”,1);
The variable holds a reference to a particular object, it refers to this object; we can interact with the object through a variable that refers to it
31unit 4
References: implementationReferences: implementation
In practice, an object reference holds the memory address of an object
Rather than dealing with arbitrary addresses, we often depict a reference graphically as a “pointer” to an object
ChessPiece bishop1 = new ChessPiece(“bishop”,”b”,1);
bishop1
32unit 4
References: declarationReferences: declaration
The declaration of the object reference variable and the creation of the object are separate activities.
We declare a variable named bishop1 whose type is ‘a reference to ChessPiece’:
ChessPiece bishop1;
bishop1 can store a reference to an instance of class ChessPiece. However, no ChessPiece object is created yet and the value of bishop1 is undefined!
33unit 4
References: instantiationReferences: instantiation
We now create a new Chesspiece object and store the reference to it in the variable bishop1:
bishop1 = new ChessPiece(“bishop”,”b”,1);• In a later stage of the program, bishop1 can be set to
refer to another object, but it can only refer to a Chesspiece 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.
bishop1 = null;
34unit 4
Interaction with objects: methodsInteraction with objects: methods
We interact with an object by means of method invocation:
bishop1.captured();
Sometimes the invocation requires parameters:bishop1.move(i,j);
Some methods also have a return value: l = bishop1.locate();
35unit 4
Assignment RevisitedAssignment Revisited
The act of assignment takes a copy of a value and stores it in a variable
For primitive types:
num2 = num1;
Before
num1
5
num2
12
After
num1
5
num2
5
36unit 4
Object Reference AssignmentObject Reference Assignment
For object references, assignment copies the memory location:
bishop2 = bishop1;
Before
bishop1 bishop2 bishop1
After
bishop2
37unit 4
Example: Reference AssignmentExample: Reference Assignment
Bucket bucket1 =
new Bucket(4);
bucket1.fill();
Bucket bucket2 =
new Bucket(2);
bucket2.fill();
bucket1bucket2
bucket1bucket2
38unit 4
Example: Reference AssignmentExample: Reference Assignment
bucket1 = bucket2;
int quantity =
bucket1.getQuantity();
// quantity = 2bucket1bucket2
bucket1bucket2
39unit 4
AliasesAliases
Two or more references that refer to the same object are called aliases of each other
One object (and its data) can be accessed using different variables
Aliases can be useful, but should be managed carefully
Changing the object’s state (its variables) through one reference changes it for all of its aliases
40unit 4
Garbage CollectionGarbage 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
41unit 4
OOP: EncapsulationOOP: Encapsulation
You can take one of two views of an object:• internalinternal - the structure of its data, the algorithms
used by its methods
• externalexternal - the interaction of the object with other objects in the program
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 goal is abstraction: objects hiding details from
the rest of the systembad example: year 2000 bug
42unit 4
EncapsulationEncapsulation
An object should be self-governing
Any changes to the object's state (its variables) should be accomplished by that object's methods
We should make it difficult, if not impossible, for one object to "reach in" and alter another object's state
The user, or client, of an object can request its services, but should not have to be aware of how those services are accomplished
43unit 4
EncapsulationEncapsulation
An encapsulated object can be thought of as a black box
Its inner workings are hidden to the client, which only invokes the interface methods
ClientClient Methods
Data
44unit 4
Encapsulation & Visibility ModifiersEncapsulation & Visibility Modifiers
In Java, we accomplish encapsulation through the appropriate use of visibility modifiers
A modifier is a Java reserved word that specifies particular characteristics of a method or data value
We've used the modifier final to define a constant
Java has three visibility modifiers: public, private, protected, or none
We will discuss the protected modifier later
45unit 4
Visibility ModifiersVisibility Modifiers
We use the generic term member to describe a variable, a method or a constructor of the class
Members of a class that are declared with public visibility can be accessed from anywhere; service methods are declared public
Members of a class that are declared with private visibility can only be accessed from inside the class; usually instance variables are declared private
Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package
46unit 4
Public VisibilityPublic Visibility
Members that are declared as public can be accessed from any class that can access the class of the member: they are part of the interface of the class
Example: the methods captured(), move() and locate() are part of the interface of class ChessPiece so we define them as public
We do not want to reveal the internal representation of the object’s data. So we usually do not declare its state variable as public (encapsulation)
47unit 4
Private VisibilityPrivate Visibility
A class member that is declared as private, can be accessed only by code that is within the class of this member
We hide the internal implementation of the class by declaring its state variables and auxiliary methods as private
Data hiding is essential for encapsulation
48unit 5
// Example of illegal access
class ChessPieceTest {
public static void main(String[] args) {
ChessPiece bishop1 =
new Chesspiece(“bishop”,`b`,1);
bishop1.state = “captured”;
// this will not compile!
}
}
49unit 4
Changing the Implementation of a ClassChanging the Implementation of a Class
Encapsulation allows us to change an implementation of a class without affecting other parts of the program.
Without encapsulation changes to implementation might “break” the program
Why would we want to change the implementation?• Different implementations have different tradeoffs
(e.g., space conservation, efficiency etc.)
50unit 4
Visibility Modifiers: rulesVisibility Modifiers: rules
No object's data should be declared with public visibility
Methods that provide the object's services (service methods) are usually declared with public visibility so that they can be invoked by clients
A method created simply to assist a service method (support method) is usually declared with private visibility