61
1 Object and Classes Lesson #3 Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently M. Deek.

1 Object and Classes Lesson #3 Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek

  • View
    217

  • Download
    1

Embed Size (px)

Citation preview

1

Object and Classes

Lesson #3

Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek.

2

Contents

Objects Messages Classifications Classes Instances Metaclasses

3

Object-based Programming

One way to view the world is as a collection of autonomous, interacting objects. Examples: people, animals, plants,

buildings, rooms, stairs, ...

4

Real-World Object Properties

Active, autonomous behavior not directly controlled by the outside

Communicative can "send messages" to other objects

Collaborative long-term relationships between objects will

arise

5

Real-World Object Properties Nested

complex objects have other objects as components (which in turn may have object components...)

Uniquely named (though not always – trade-off between

short names and unambiguous names) Creation/Destruction

May be created and destroyed

6

Examples

A person Thinks (most of the time) Communicates with others Collaborates and works with others Has a Name (and a SSN) Is born/then dies

7

Examples

A room Autonomous and Communicative (Arguable)

“open” is a message sent to a person to open a door, “open” is part of the room’s attributes.

Collaborative Accept the messages from other objects, and sends

messages to other objects based on your view on the room

Room No. Built/Destroyed

8

Examples

A computer Autonomous: it can do many things Communicative (with people, with other

computers) A serial No. Built/Destroyed

9

Virtual Objects

Objects that exist in programs only: Virtual objects consist of the above

features. Virtual objects are much more precise in

their name, borders, interactions, etc. Virtual objects are the basic components

for you object-oriented programs.

10

Examples of Virtual Objects

A Bank Account Has a balance; responds to messages for

deposits, withdrawals, and balances.

Set Elements can be added, deleted, and queried.

11

Examples of Virtual Objects

E-Ticket record that customer has paid for service

in advance of flight Payment

an event (transaction?) in which money is exchanged

12

Virtual Object Example: a Set

The external view (signature): aSet understands the messages

aSet.add(anElement) aSet.remove(anElement) aSet.contains(anElement) aSet.size()

Messages have both an effect (internal changes or induced messages) and a return value.

Users only need external view of aSet to use it.

13

Internal view Instance variables for aSet:

hashArray, valueArray Instance variables are private for just

that object and have indefinite extent For each message, there exists a

method to perform the action

14

Sets in non-object-based languages

The Set itself is a (passive) struct with an array and a hash table

Operations on the set are active but stateless functions: procedure add(s:Set,e:Element)... procedure remove(s:Set,e:Element)... procedure contains(s:Set,e:Element) (stateless functions don't remember

anything from one call to the next)

15

Sets in non-object-based languages

Note there is no encapsulation: The programmer could directly manipulate

the data, possibly putting the data in a compromised state.

16

What are Objects?

Booch: Something that “has state, behavior, and identity.”

Martin/Odell” “Anything, real, or abstract, about which we store

data and those methods (operations) that manipulate the data.”

Peter Müller: An object is an instance of a class. It can be

uniquely identified by its name and it defines a state which is represented by the values of its attributes at a particular time.

17

Message (Definition )

A message is a request to an object to invoke one of its methods. A message therefore contains the name of the method and the arguments of the method.

Consequently, invocation of a method is just a reaction caused by receipt of a message. This is only possible when the method is actually known to the object.

18

The Interface

The operation name list open to other objects.

If an object has a function but does not show it to the public, this is useless for the public (called private function).

In C++, only public functions (belong to the interface) can be called (through messages such as a.fun()) by other objects.

19

Again, Examples of objects

ID: SSN

Operations:EatWalkWork…

A person:

States:

Name

Sex

Age

Interface:What is in a person’s resume…

20

Examples of objects

ID: ISBN

A book OperationsBuyOpenGet infoCloseDiscard

States:TitleAuthorPublisher Interface

All the above operation names

21

Properties of Objects

Encapsulation (Data & Operations) Information Hiding Data Abstraction (with classes) Abstract Data Type (with classes)

22

ADVANTAGES OF OBJECTS

Same as abstract data types Information hiding Data abstraction Procedural abstraction

Inheritance provides further data abstraction Easier and less error-prone product

development Easier maintenance

23

Classification

Classification is not unique to object-oriented systems. On the contrary, classification is applied in many other domains.

Peter Wegner gave the description about classification (1986).

24

Classification An object can be "of" a certain class, but not

its creator. An apple is of Fruit, but is not the instance of Fruit.

In this view, classes are like sets. John is a man. Jane is a woman. Spot is a dog. All men are people. All women are people. All people are mammals. All dogs are mammals.

25

Classification

Mammal

People

Bird

Dog

Animal

man woman

John Jane

. . . . .

26

Class

A class is either a classification or an abstraction of objects.

Class is not only an concept, but also a practical mechanism of programs.

Object-Oriented programming is actually programming-with-classes.

27

Classes ”Class - a definition of an

implementation (methods and data structures) shared by a group of objects"

”Class - a template from which objects may be created. It contains a definition of the state descriptors and methods for the object."

28

Classes

Classes serve two distinct purposes Factories that create new objects

(code plus specification) Classifications of objects

(specification only: e.g. sizable class is any object with a size method)

29

Intentional notion of Class

New objects are instances of a class. Their state and behavior are determined by the class definition.

This is the so-called intentional notion of a class.

The intentional notion determines the structure of instances of that class.

30

Extensional Notion of Class

A class consists of object-warehouse and object-factory.

Object warehouse means that a class implicitly maintains a class extent.

A class extent consists of all instances of one class. Object-factory means that there exists a constructor for each class.

The purpose of this constructor is to generate new instances of a class.

31

Understanding Classes

A class provides a definition of the structure of instances of that class.

The class defines the names of attributes (state) and methods (behavior) of an object belonging to this class.

32

What is a Class

A class is a user-defined type. Booch:

“A set of objects that share a common structure and common behavior”

33

Class ::=<Id, Ds, Ops, Intfc>, where Id is the Identification or name of the

class; Dt is the space description (template) for

memory; Op is the set of the operations’

implementation the objects of this class can make;

Int is the unify interface of the objects of the class.

34

A class(Similar to C++)

class Integer {Ds:

int IOps:

setValue(int n)Integer addValue(Integer j)

}

35

Examples of class

class horse{ Ds:

Age Weight Color

Ops: Drag Run ride

}

36

Examples of class class building{ Ds:

Name Architecture Height Time built Builder

Ops: Open Enter Leave …

}

37

Relationships among Classes

Link(use-a) A link relationship exists between two

classes that need to communicate (an instance of one class sends a message to an instance of another class).

Composition (has-a) A composition relationship exists when a

class contains data members that are also class class objects.

38

Instantiation

The mechanism of creating new objects from a class definition is called instantiation.

Every class has such a mechanism.

39

Instantiation

Static instantiation and Dynamic instantiation. instantiation at compile time; instantiation at run time.

Dynamic instantiation requires run-time support for allocation and de-allocation of memory.

40

Making objects from class templates

aSet = new Set() /*Set is the class; this makes an object*/

anotherSet = new Set() /*Same factory, but different contents*/

Each time an object created, it is new and unique

41

Object ::= <Oid, Cid, Body>, where Oid is the identification or name of the

object; Cid is the identification or name of the

class of this object; Body is the actual space for memory;

Note: the operations of the object are implemented in the class.

42

Instantiation Examples

bk = new Book ( Actually in the Publishing House);

bldg = new Building ( Actually by workers)

child = new Person ( Actually by parents)

43

Examples of Class in C++

#include <iostream.h> // Stream I/O Class Library

#include <stdio.h> // Standard Header File

#include <math.h> // Math Library: need acos() declaration

const double PI = acos( -1.0 ) ;

typedef float Radius ;

typedef float Coordinate ;

typedef bool Boolean ;

#define NUM_SAMPLES 4

//ex3class.cpp

44

ex3class.cppclass Point

{

private:

Coordinate x , y ;

public:

Point() ; // default constructor

Point( Coordinate new_x ) ;

Point( Coordinate new_x, Coordinate new_y ) ;

Coordinate x_coordinate( void ) const ;

Coordinate y_coordinate( void ) const ;

Point add( const Point *p ) const ;

Point add( const Point &p ) const ;

} ;

45

ex3class.cpp

Point:: Point(Coordinate new_x, Coordinate new_y)

: x ( new_x ) , y( new_y )

{}

Point:: Point(): x( 0 ) , y ( 0 ) // initialize to default values

{}

Coordinate Point:: x_coordinate( void ) const

{ return( x ) ;}

Coordinate Point:: y_coordinate( void ) const

{ return( y ) ;}

46

ex3class.cpp

Point Point:: add( const Point *p ) const{ Coordinate new_x = x_coordinate() + p->x_coordinate() ;

Coordinate new_y = y_coordinate() + p->y_coordinate() ;Point result( new_x, new_y ) ;return ( result ) ; // return result of the point addition

}Point Point:: add( const Point &p ) const{ Coordinate new_x = x_coordinate() + p.x_coordinate() ;

Coordinate new_y = y_coordinate() + p.y_coordinate() ;Point result( new_x, new_y) ;return ( result ) ; // return result of the point addition

}

47

ex3class.cpp

class Circle{

private:Point center ; // Using Point classRadius r ;

public:Circle( ) ;Circle( Coordinate x , Coordinate y , Radius radius

) ;Radius radius( void ) const ;double area( void ) const ;double circumference( void ) const ;

} ;

48

ex3class.cppCircle:: Circle( Coordinate x, Coordinate y , Radius radius )

: center( x , y ) , r( radius )

{ if( r < 0 )

{ r = fabs( r ) ; }

}

Circle:: Circle( ): center( ) , r( 0 ) // initialization list

{}

Radius Circle:: radius( void ) const

{ return( r ) ;}

double Circle:: area( void ) const

{ return( PI * r * r ) ;}

double Circle:: circumference( void ) const

{ return( 2 * PI * r ) ;}

49

ex3class.cpp

void interactive_test( void ) ;Boolean test_circle( void ) ;float sample_list[NUM_SAMPLES] ={ -12.0 , 4.0 , 3.0 , 0.0} ;int main( int , char ** ){// interactive_test() ;

if( test_circle() ){cout << " \n\t Functional Tests ............... Passed\n" ; }else{cout << " \n\t Functional Tests ............... Failed\n" ; }return( 0 ) ;

}

50

ex3class.cppvoid interactive_test( void )

{Circle c1( 1 , 3 , 4.0 ) ;

cout << "\n ** Created a Circle at (1,3) with radius = " << c1.radius( ) ;

printf("\n -- Using Standard I/O to Show radius: %f", c1.radius( ) ) ;

Radius radius ;

cout << "\n\n ** To create a new Circle Object, input value for radius: " ;

cin >> radius ;

cout << "\n\n ** Value of PI = " << PI ; // output results

Circle c2( 0 , 0 , radius ) ;

cout << "\n ** Created a Circle at origin with radius = " << c2.radius( ) ;

cout << "\n ** Circle's area = " << c2.area() ;

return ;

}

51

ex3class.cpp

Boolean test_circle( void )

{ Boolean test_passed = true ;

double current_area , current_circum ;

float r ;

for( int i = 0 ; i < NUM_SAMPLES ; i++ )

{ Circle c( 0 , 0 , sample_list[i] ) ;

r = (float) fabs( sample_list[i] ) ;

current_area = PI * r * r ;

current_circum = 2 * PI * r ;

52

ex3class.cpp

if( current_circum < 0 )

{current_circum = -current_circum ;}

if( c.area() != current_area )

{test_passed = false ;

cout << "\n\t " << i + 1 << " . Circle's radius = " << r ;

cout << "\n\t Expected Area: " << current_area

<< "\n\t Actual Area : " << c.area() ;

break ;

}

53

ex3class.cpp

else if( c.circumference() != current_circum )

{test_passed = false ;

cout << "\n\t " << i + 1 << " . Circle's radius = " << r ;

cout << "\n\t Expected Circum: " << current_circum

<< "\n\t Actual Circum : " << c.circumference() ;

break ;

}

54

ex3class.cpp

else if( c.radius() != r )

{test_passed = false ;

cout << "\n\t " << i + 1 << " . " ;

cout << "\n\t Expected r : " << sample_list[i]

<< "\n\t Actual r : " << c.radius() ;

break ;

}

}

return( test_passed ) ;

}

55

56

The Relations between Class and Objects

A class is an object? An object is an instance of a class? “Then, what is the class of a class?

The metaclass

57

Meta class

A meta class is the class of a class. The attributes of a meta class can be

used to describe a class (e.g. # of instances of a class).

58

Meta class

Explicit support of meta classes means that objects, classes and meta classes are treated uniformly.

Classes can be created at run-time by explicitly sending a message to a special metaclass.

59

Metaclass

Metaclasses are hidden from the user. A metaclass hierarchy is maintained

parallel to the class hierarchy.

60

Metaclass

In C++, there is a metaclass in the compiler. Because each class definition is an instance of a class in the compiler which demonstrates the structures of classes.

61

Readings

Chapter 2 Section 2.1