What is Object? Using Brian Mitchell’s notes for reference

50
1 What is Object? Using Brian Mitchell’s notes for reference Objects are tangible entities that exhibit some well defined behavior Some typical object characteristics: 1. A tangible or visible thing 2. Something that may be apprehended intellectually 3. Something toward which thought or action is directed Text book definition: An object has state, behavior, and identity; the structure and behavior of similar objects are defined in their common class` ( Inheritance )

description

3 Characteristics of an object State Behavior Identity Example: All of the objects that are depicted in the above window have an active state, well defined behavior and unique identity Climate Control System Ignition CD Player Buttons Equalizer Shift

Transcript of What is Object? Using Brian Mitchell’s notes for reference

Page 1: What is Object? Using Brian Mitchell’s notes for reference

1

What is Object? Using Brian Mitchell’s notes for reference

Objects are tangible entities that exhibit some well defined behavior

Some typical object characteristics:1. A tangible or visible thing2. Something that may be apprehended

intellectually3. Something toward which thought or action is

directedText book definition: An object has state, behavior,

and identity; the structure and behavior of similar objects are defined in their common class` ( Inheritance )

Page 2: What is Object? Using Brian Mitchell’s notes for reference

2

3 Characteristics of an object State Behavior IdentityExample:

All of the objectsthat are depicted in the above window have an active state, well defined behavior and

uniqueidentity

Equalizer

Ignition

CD Player

Climate ControlSystem

Buttons

Shift

Page 3: What is Object? Using Brian Mitchell’s notes for reference

3

Objects Objects are active entities (identity) Objects exits at run time Objects store information that is the result of

prior operations ( the object state ) Current state of the object can be used to

determine how object carries out its operations in future ( State Machine )

The current state of the object always represents the consequences of all the previous operations that were performed on the object. Object’s state does not change spontaneously !

Page 4: What is Object? Using Brian Mitchell’s notes for reference

4

Object State Definition: The state of an object

encompasses all of the (usually static ) properties of the object plus the current (usually dynamic ) values of each of these properties.

State is defined by the current values of the object properties.

A property of an object is an inherent or distinguishing characteristic, trait, quality of feature that contributes to defining the uniqueness of the object

Page 5: What is Object? Using Brian Mitchell’s notes for reference

5

Object Properties Properties are usually static ( i.e.,

we can not dynamically create new object properties) All properties must contain valid

values Must be enforced by object’s behavior State may effect the behavior of an

object

Page 6: What is Object? Using Brian Mitchell’s notes for reference

6

Example representing object’s state:class Person{

public:string name;long int ssn;string address;

};int main() {

Person * p = new Person();Person * p2 = new Person(); p->name = “John Smith”;p->ssn = 123456789;// …return 0;

}

Objects state is determined by the current values of the objects properties. The object properties are contained within the member variables of the class.

Page 7: What is Object? Using Brian Mitchell’s notes for reference

7

Example of Object State In the example name, ssn, and address represent

properties of the Person class. The Person class declaration is used to define object’s

structure. Class declaration DOES not create actual objects All objects must be created from valid class definitions. The

pointer variables p and p2 points to an actual (distinct) objects.

p and p2 point to distinct instances of object Person, even though they were created from the same class

Both instances share common structure (common set of properties and behavior ), but reside in different memory addresses as unique entities.

Page 8: What is Object? Using Brian Mitchell’s notes for reference

8

Encapsulating the state of an object It is a good engineering principle to encapsulate

the state of an object rather than exposing it to outside users

Promotes data hiding Enables object’s designer to control access to the

internal object’s state Protects the internal integrity of the object Enables design decisions to be changed later without

impacting external object users. As long as public interface is the same, internal

behavior of object can change without affecting external users

Page 9: What is Object? Using Brian Mitchell’s notes for reference

9

Example of encapsulation:class Person{

public:inline int getSSN() const;inline int setSSN(const int newSSN);inline int setName(const string & name);inline string getName() const;

private:string name;int ssn;

};

Page 10: What is Object? Using Brian Mitchell’s notes for reference

10

Example of encapsulation:int Person :: getSSN() const {

return ssn;}int Person :: setSSN(const int newSSN){

if( newSSN == 0 ) // Protect attributes from malicious users !!!return 1; // Error !

this->ssn = newSSN;return 0; // Success

}int Person :: setName(const string & name){

if ( name == “” ) // Protect attributes from malicious users !!!return 1; // Error !

this->name = name; return 0; // Success

}string getName() const {

return name;}

Page 11: What is Object? Using Brian Mitchell’s notes for reference

11

Encapsulation/State summary The internal object representation is hidden from outside

users If we change internal representation of the object, no

client will be affected by the change, this facilitates reuse. We explicitly defined the operations that are allowed to

be performed on the object. Only special clients (subclasses via inheritance) will have

permission to directly modify the internal state of the object

All objects within the system encapsulate some state and that the state within a system is encapsulated by objects

Page 12: What is Object? Using Brian Mitchell’s notes for reference

12

Object Behavior Definition: Behavior is how an object acts and reacts, in term

of its state changes and message passing. Behavior is visible and testable Current state of an object represents cumulative results of its

behavior Objects can be acted upon, or they can act on other objects All objects allow certain operations while not supporting

others The set of operations allowed to act upon an object define its

behavior Not all operations are suitable or implemented for a given

object. Mechanism must exist to reject improper or unsupported requests.

Page 13: What is Object? Using Brian Mitchell’s notes for reference

13

Behavior Behavior can be rejected statically ( Compile

time error ), or dynamically ( Runtime error or runtime exception )

Object behavior can be updated at a later time to support new versions of the object.

The set of supported operations on an object must always make sense with respect to the definition of the objects definition. Example: When you press brake pedal in your car,

- you expect your car to stop, not accelerate.

Page 14: What is Object? Using Brian Mitchell’s notes for reference

14

Operations An operation denotes a service that a class offers

to its clients There are five different kinds of operations that a

client may perform on an object: Modifier: An operation that alters the state of an object Selector: An operation that access the state of an

object, but does not alter the state Integrator: An operation that permits all parts of an

object to be accessed in some well-defined order Constructor: An operation that creates an object and/or

initializes its state Destructor: An operation that frees the state of an

object and/or destroys the object itself

Page 15: What is Object? Using Brian Mitchell’s notes for reference

15

Roles and Responsibilities Collectively, all of the methods

associated with a particular object comprise its protocol. Protocol defines the envelop of

allowable behavior Protocol comprises the entire static

and dynamic view of the object Roles of the object define allowable

behavior of the object

Page 16: What is Object? Using Brian Mitchell’s notes for reference

16

Roles and Responsibilities Responsibilities:

Knowledge that the object must maintain

Actions that the object is allowed to perform

Services that the object provided for all of the contracts that it supports

Page 17: What is Object? Using Brian Mitchell’s notes for reference

17

Objects As State Machines The current behavior of an object is often

influenced by its history The existence of state within an object

means that the order in which operations are invoked are important. Example: Network protocols (TCP protocol )

Object behavior is event and time driven Each object acts like a tiny, independent

machine

Page 18: What is Object? Using Brian Mitchell’s notes for reference

18

Active and Passive objects A passive object can only under a state

change when it is explicitly acted upon. An active object encompasses its own

thread of control Active objects are generally autonomous Active objects can exhibit some behavior

without being operated upon by another object Example: An object responsible for controlling a

game simulation Every OO system must have at least one active

object

Page 19: What is Object? Using Brian Mitchell’s notes for reference

19

Object identity Identity is a property that distinguishes

an object from all other objects The failure to recognize the difference

between the name of an object and the object itself is the source of many kinds of errors in OO programming

The current object state and the collection of allowable operations do not fully characterize the object.

Page 20: What is Object? Using Brian Mitchell’s notes for reference

20

Object identity It is possible for two or more distinct

objects to have the same state and support the same operations. Because objects are distinct they each have their own identity, thus they are different.Car * c1 = new Car(“bmw”);Car * c2 = new Car(“bmw”);

c1 and c2 both support the same operations and the same state, yet they have different identities

Page 21: What is Object? Using Brian Mitchell’s notes for reference

21

Copying, Assignment & Equality of Objects Structural sharing takes place when the identity of

an object is aliased to a second name This arrangement may leads to two or more

variable names that operate on the same object Copy Operation is performed by a copy constructor When a copy operation is performed on an object,

a new object must be created and the state of the first object must be loaded into the new object

Car x(“bmw”); Car y(x);

Page 22: What is Object? Using Brian Mitchell’s notes for reference

22

Assignment Operation The assignment operator by default will

create an alias of the original object. Most languages allow to override the default behavior of the assignment operator.

Issues of doing Shallow and Deep copy. Be careful !

Car x(“bmw”); Car y=x; // By default calls copy

constructor unless constructor is declared explicit

Page 23: What is Object? Using Brian Mitchell’s notes for reference

23

Equality Operation The equality operation can check

to see if two names designate the same object, or if two names designate distinct objects that have the same state.

In C++ operator== investigates if two objects are aliases of each other.

Page 24: What is Object? Using Brian Mitchell’s notes for reference

24

Object Life Span The lifetime of an object extends

from the time it is first created until the time it is explicitly destroyed

Objects in C++ are created by either declaration or allocation

Car x(“bmw”); // By declaration Car * x = new Car(“bmw”); // Allocation

Page 25: What is Object? Using Brian Mitchell’s notes for reference

25

Object lifespan Objects are destroyed in C++ in one of two

ways: If the object was created by declaration, it is

destroyed when the variable that is representing object goes out of scope.

Example: { … } block end or function return. If the object was created by allocation, it is

destroyed when the programmer issues the delete instruction. Otherwise, you get lost memory.

Car * p = new Car(“bmw”); delete p;

Page 26: What is Object? Using Brian Mitchell’s notes for reference

26

Object lifespan Objects are destroyed in Java by an automatic housecleaning

process. That is the object is destroyed, when there are no more references to the object.

Whenever an object is created, its constructor is automatically called so that proper initialization can be performed

Whenever an object is destroyed its destructor is automatically called so that the object can perform any necessary cleanup

Objects allocated dynamically on heap, must be explicitly de allocated by the programmer executing delete operation

In Java an object is terminated when it is explicitly destroyed once all references to the object are broken. Cleanup is performed automatically using garbage collection algorithm

Page 27: What is Object? Using Brian Mitchell’s notes for reference

27

Lifespan and Persistence Persistent objects have slightly different

semantics regarding destruction When object is deleted, its full state is

stored into persistent database on hard driver ( non-volatile storage )

Later on, object’s state can be loaded back from the persistent storage.

Page 28: What is Object? Using Brian Mitchell’s notes for reference

28

Classes Programming is largely a matter of subcontracting

The various functions of a larger problem are decomposed into smaller problems by subcontracting them to different elements of the design

The class is used to capture the structure and behavior that is common to all related objects that are created from the same class

Individual object is a concrete entity that performs some role in the overall system. It’s a template for creating a collection of related objects

All objects of the same class support the same collection of operations and have a common set of possible states

Page 29: What is Object? Using Brian Mitchell’s notes for reference

29

Classes A class is a template or definition that is used to create an

object. The class definition describes the structure and behavior of

an object Objects that conform to a class description are instances of

the class The class definition is used to create a set of objects that

share a common structure and behavior. A class description must list operations that are allowed on

objects of the class, and possible states for the objects of the class defined through class properties.

A class is not an active entity Classes are described in source code Objects created from classes, and exit at run time

Page 30: What is Object? Using Brian Mitchell’s notes for reference

30

Classes A class represents a set of objects

that share a common structure and common behavior. Example: car Class: Class car Object: The actual cars

Page 31: What is Object? Using Brian Mitchell’s notes for reference

31

Example: Class Mailbox Recall that a class definition must

describe the operations that are allowed on objects of the class and the possible states for objects of the class

Class Mailbox Operations:

Add a message List all stored messages Delete a message Show a particular message

Page 32: What is Object? Using Brian Mitchell’s notes for reference

32

Example: Mailbox Properties: Linked list of messages Note that a “Message” is abstract

with respect to class Mailbox Message could be

Buffer of raw data May be defined by a struct May be objects defined by another

class (Message )

Page 33: What is Object? Using Brian Mitchell’s notes for reference

33

Interface and Implementation A class has both an outside view and an

inside view The interface of the class represents the outside

view Emphasis is placed on the providing the correct

level of abstraction The interface is also used to protect the classes

internal structure and the secrets of its behavior The interface includes the declaration of all the

operations applicable to instances of this class ( methods), declarations of other classes(nested classes), constants, variables and exceptions

Page 34: What is Object? Using Brian Mitchell’s notes for reference

34

Interface and Implementation The implementation of a class

represent its inside view The implementation is used to

encompass the secrets of the classes behavior. Algorithms and data structures

Page 35: What is Object? Using Brian Mitchell’s notes for reference

35

Class Access Rights In both the Java and C++ programming

languages the interface of a class can be broken down into three parts:

Public, protected, and private The class interface can be divided into

distinct sections whereby each section can be protected by any one of the three available access control rights

The developer must decide which protection mechanism to use

Page 36: What is Object? Using Brian Mitchell’s notes for reference

36

Class Access Rights Public – A declaration that defines that results in

all class attributes being accessible to all clients Protected – A declaration that causes the class

attributes to be accessible only to the class itself and its subclasses ( via inheritance )

Private – A declaration that causes the class attributes to be accessible only to the class itself.

Exception: friend functions and classes Friends are not supported by Java, only C++

Page 37: What is Object? Using Brian Mitchell’s notes for reference

37

Class Access Rights Exampleclass BankAcct{

private:string address;string name;int balance;

public:int getBalance() const;string getName() const;int setName(const string & name);// …

};

Page 38: What is Object? Using Brian Mitchell’s notes for reference

38

Class types In the early stage of OO Design you

need to select classes Most classes can be categorized by the

following types Data Managers, Data or State classes. To

maintain data or state information. Example “playing card”

Data Sinks or Data Sources: classes that accept data, and classes that generate data

Page 39: What is Object? Using Brian Mitchell’s notes for reference

39

Class types Facilitator or Helper classes

Classes that maintain little of no state information but assist in the execution of complex task – an interest calculation class

View of Observer classes Classes that display or visualize

information Data views are usually independent of the

actual data tat is being displayed

Page 40: What is Object? Using Brian Mitchell’s notes for reference

40

Class Relationships Classes usually do not exist in isolation.

Example: objects that compose a car Classes are generally related in a variety

of ways The relationship between classes is used

to construct the class structure of a system design

We are interested in exploiting the similarities between classes for software reuse

Page 41: What is Object? Using Brian Mitchell’s notes for reference

41

Class Relationships Example: A class may be thought of as

a specialized version of another class Desire to exploit similarities between

classes Most operations are identical or similar,

however, there might be a few differences This is the inheritance relationships, we

will study inheritance later

Page 42: What is Object? Using Brian Mitchell’s notes for reference

42

Class RelationshipsExample Employee has name, address, salary,

Department Manager is an employee. Manager must also

manage the employees that work for the manager. Manager manages a list of employee

Engineer is an employee, but engineer is a special type of employee

This is “is a relationship”Employee

Manager Engineer

Page 43: What is Object? Using Brian Mitchell’s notes for reference

43

Class Relationships types There are three basic kinds of class

relationships Generalization/Specialization. This is

inheritance, and denotes an “is a” relationship Manager “is an” Employee

Aggregation/Containment. This denotes a “part of” relationship

Example: Car contains transmission Association: This denotes a semantic

dependency among otherwise unrelated classes Manager can “use” employees to solve tasks

Page 44: What is Object? Using Brian Mitchell’s notes for reference

44

Association Association is a way of

representing a bi-directional relationship between two objects

Common association cardinalities One-to-one One-to-many Many-to-many

Page 45: What is Object? Using Brian Mitchell’s notes for reference

45

Aggregation Aggregation is used to enable

objects to physically contain other objects

Aggregation asserts a direction to the whole/part of relationship

Page 46: What is Object? Using Brian Mitchell’s notes for reference

46

Using “Using” relationships among classes parallel

peer-to-peer links among the corresponding instances of these classes

A “Using” relationship among classes requires the designer to specify which class ( or set of classes ) are users of service and which class ( or classes ) are the suppliers of the service

A “Using” relationship usually takes the form of an object created as a local variable or an object being passed to a member function as a parameter

Page 47: What is Object? Using Brian Mitchell’s notes for reference

47

Using example void MailBox::Print(string & msg ) { cout << msg; } In the above example, the string class is not “part of” the mailbox class, nor does it specialize it – it is a Using relationship

Page 48: What is Object? Using Brian Mitchell’s notes for reference

48

Instantiation Instantiation is the act of providing

additional information to a class that is required before instances of that class can be created

Instantiation is generally required when we want to build “type-safe” classes.

In C++ instantiation is facilitated by using templates. A well documented shortcoming of Java is its lack of template support

Page 49: What is Object? Using Brian Mitchell’s notes for reference

49

Example of instantiationGarray<BankAcct> * gaAcct = new Garray();Garray<WidgetMgmt> * gaWidget = new Garray();

BankAcct * ba = new BankAcct();BankAcct * ba1 = new BankAcct();ba->setAcctNum(12345);ba1->setAcctNum(123456);gaAcct->AddItem(ba);gaAcct->AddItem(ba1);gaWidget->addItem(ba); // causes error

Page 50: What is Object? Using Brian Mitchell’s notes for reference

50

Relationship among classes Most object oriented languages

provide the following mechanisms for capturing the relationships among classes Association Inheritance Aggregation Using Instantiation