Object and Classes Lesson 3 1 Note CIS

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

Contents u Objects u Messages u Classifications u Classes u Instances u Metaclasses 2

Object-based Programming u One way to view the world is as a collection of autonomous, interacting objects. u Examples: people, animals, plants, buildings, rooms, stairs, . . . 3

Real-World Object Properties u Active, u not autonomous behavior directly controlled by the outside u Communicative u can "send messages" to other objects u Collaborative u long-term arise 4 relationships between objects will

Real-World Object Properties u Nested u complex objects have other objects as components (which in turn may have object components. . . ) u Uniquely named u (though not always – trade-off between short names and unambiguous names) u Creation/Destruction u May 5 be created and destroyed

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

Examples u. A room u Autonomous u and Communicative (Arguable) “open” is a message sent to a person to open a door, “open” is part of the room’s attributes. u Collaborative u Accept the messages from other objects, and sends messages to other objects based on your view on the room u Room No. u Built/Destroyed 7

Examples u. A computer u Autonomous: it can do many things u Communicative (with people, with other computers) u A serial No. u Built/Destroyed 8

Virtual Objects u Virtual that exist in programs only: objects consist of the above features. u Virtual objects are much more precise in their name, borders, interactions, etc. u Virtual objects are the basic components for you object-oriented programs. 9

Examples of Virtual Objects u. A Bank Account u Has a balance; responds to messages for deposits, withdrawals, and balances. u Set u Elements 10 can be added, deleted, and queried.

Examples of Virtual Objects u E-Ticket u record that customer has paid for service in advance of flight u Payment u an event (transaction? ) in which money is exchanged 11

Virtual Object Example: a Set u The u external view (signature): a. Set understands the messages a. Set. add(an. Element) u a. Set. remove(an. Element) u a. Set. contains(an. Element) u a. Set. size() u u Messages have both an effect (internal changes or induced messages) and a return value. u Users only need external view of a. Set to use it. 12

Internal view u Instance variables for a. Set: u hash. Array, u Instance value. Array variables are private for just that object and have indefinite extent u For each message, there exists a method to perform the action 13

Sets in non-object-based languages u The Set itself is a (passive) struct with an array and a hash table u Operations on the set are active but stateless functions: u procedure add(s: Set, e: Element). . . u procedure remove(s: Set, e: Element). . . u procedure contains(s: Set, e: Element) u (stateless functions don't remember anything from one call to the next) 14

Sets in non-object-based languages u Note there is no encapsulation: u The programmer could directly manipulate the data, possibly putting the data in a compromised state. 15

What are Objects? u Booch: u Something that “has state, behavior, and identity. ” u Martin/Odell” u “Anything, real, or abstract, about which we store data and those methods (operations) that manipulate the data. ” u Peter u An Müller: 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. 16

Message (Definition ) u. A message is a request to an object to invoke one of its methods. A message therefore contains u the name of the method and u the arguments of the method. u 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. 17

The Interface u The operation name list open to other objects. u If an object has a function but does not show it to the public, this is useless for the public (called private function). u In C++, only public functions (belong to the interface) can be called (through messages such as a. fun()) by other objects. 18

Again, Examples of objects A person: ID: SSN u. States: u. Name u. Sex u. Age 19 u. Operations: u. Eat u. Walk u. Work u… u. Interface: u. What is in a person’s resume…

Examples of objects u. A book u ID: ISBN u. States: u. Title u. Author u. Publisher u. Operations u. Buy u. Open u. Get info u. Close u. Discard u. Interface u. All 20 the above operation names

Properties of Objects u Encapsulation (Data & Operations) u Information Hiding u Data Abstraction (with classes) u Abstract Data Type (with classes) 21

ADVANTAGES OF OBJECTS u Same u u u as abstract data types Information hiding Data abstraction Procedural abstraction u Inheritance abstraction u Easier provides further data and less error-prone product development u Easier maintenance 22

Classification u Classification is not unique to objectoriented systems. On the contrary, classification is applied in many other domains. u Peter Wegner gave the description about classification (1986). 23

Classification u An object can be "of" a certain class, but not its creator. u An u In apple is of Fruit, but is not the instance of Fruit. this view, classes are like sets. u John is a man. Jane is a woman. u Spot is a dog. u All men are people. All women are people. u All people are mammals. All dogs are mammals. 24

Classification Animal Mammal People man John 25 Dog woman Jane Bird. . .

Class u. A class is either a classification or an abstraction of objects. u Class is not only an concept, but also a practical mechanism of programs. u Object-Oriented programming is actually programming-with-classes. 26

Classes u ”Class - a definition of an implementation (methods and data structures) shared by a group of objects" u ”Class - a template from which objects may be created. It contains a definition of the state descriptors and methods for the object. " 27

Classes u. Classes serve two distinct purposes u. Factories that create new objects (code plus specification) u. Classifications of objects (specification only: e. g. sizable class is any object with a size method) 28

Intentional notion of Class u New objects are instances of a class. Their state and behavior are determined by the class definition. u This is the so-called intentional notion of a class. u The intentional notion determines the structure of instances of that class. 29

Extensional Notion of Class u. A class consists of object-warehouse and object-factory. u Object warehouse means that a class implicitly maintains a class extent. u A class extent consists of all instances of one class. Object-factory means that there exists a constructor for each class. u The purpose of this constructor is to generate new instances of a class. 30

Understanding Classes u. A class provides a definition of the structure of instances of that class. u The class defines the names of attributes (state) and methods (behavior) of an object belonging to this class. 31

What is a Class u. A class is a user-defined type. u Booch: u “A set of objects that share a common structure and common behavior” 32

u Class u Id : : =<Id, Ds, Ops, Intfc>, where is the Identification or name of the class; u Dt is the space description (template) for memory; u Op is the set of the operations’ implementation the objects of this class can make; u Int is the unify interface of the objects of the class. 33

A class(Similar to C++) class Integer { Ds: int I Ops: set. Value(int n) Integer add. Value(Integer j) } 34

Examples of class horse{ u Ds: u u Age u Weight u Color u Ops: u Drag u Run u ride u} 35

Examples of class u u class building{ Ds: u u u Ops: u u u 36 Name Architecture Height Time built Builder } Open Enter Leave …

Relationships among Classes u Link(use-a) u. 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). u Composition u. A (has-a) composition relationship exists when a class contains data members that are also class objects. 37

Instantiation u The mechanism of creating new objects from a class definition is called instantiation. u Every class has such a mechanism. 38

Instantiation u. Static instantiation and Dynamic instantiation. uinstantiation at compile time; uinstantiation at run time. Dynamic instantiation requires run-time support for allocation and de-allocation of memory. u 39

Making objects from class templates u a. Set = new Set() /*Set is the class; this makes an object*/ u another. Set = new Set() /*Same factory, but different contents*/ u Each time an object created, it is new and unique 40

u Object : : = <Oid, Cid, Body>, where u Oid is the identification or name of the object; u Cid is the identification or name of the class of this object; u Body is the actual space for memory; u Note: the operations of the object are implemented in the class. 41

Instantiation Examples u bk = new Book ( Actually in the Publishing House); u bldg = new Building ( Actually by workers) u child = new Person ( Actually by parents) 42

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 //ex 3 class. cpp 43

ex 3 class. cpp class 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 ; }; 44

ex 3 class. 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 ) ; } 45

ex 3 class. cpp 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: : 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 } 46

ex 3 class. cpp class Circle { private: Point center ; // Using Point class Radius r ; public: Circle( ) ; Circle( Coordinate x , Coordinate y , Radius radius ) ; Radius radius( void ) const ; double area( void ) const ; double circumference( void ) const ; }; 47

ex 3 class. cpp Circle: : 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 ) ; } double Circle: : circumference( void ) const { return( 2 * PI * r ) ; } 48

ex 3 class. 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 << " nt Functional Tests. . . . Passedn" ; } else {cout << " nt Functional Tests. . . . Failedn" ; } return( 0 ) ; } 49

ex 3 class. cpp void interactive_test( void ) {Circle c 1( 1 , 3 , 4. 0 ) ; cout << "n ** Created a Circle at (1, 3) with radius = " << c 1. radius( ) ; printf("n -- Using Standard I/O to Show radius: %f", c 1. radius( ) ) ; Radius radius ; cout << "nn ** To create a new Circle Object, input value for radius: " ; cin >> radius ; cout << "nn ** Value of PI = " << PI ; // output results Circle c 2( 0 , radius ) ; cout << "n ** Created a Circle at origin with radius = " << c 2. radius( ) ; cout << "n ** Circle's area = " << c 2. area() ; return ; } 50

ex 3 class. 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 , sample_list[i] ) ; r = (float) fabs( sample_list[i] ) ; current_area = PI * r ; current_circum = 2 * PI * r ; 51

ex 3 class. cpp if( current_circum < 0 ) {current_circum = -current_circum ; } if( c. area() != current_area ) {test_passed = false ; cout << "nt " << i + 1 << ". Circle's radius = " << r ; cout << "nt Expected Area: " << current_area << "nt Actual Area : " << c. area() ; break ; } 52

ex 3 class. cpp else if( c. circumference() != current_circum ) {test_passed = false ; cout << "nt " << i + 1 << ". Circle's radius = " << r ; cout << "nt Expected Circum: " << current_circum << "nt Actual Circum : " << c. circumference() ; break ; } 53

else if( c. radius() != r ) {test_passed = false ; cout << "nt " << i + 1 << ". " ; cout << "nt Expected r : " << sample_list[i] << "nt Actual r : " << c. radius() ; break ; } } return( test_passed ) ; } 54 ex 3 class. cpp

55

The Relations between Class and Objects u. A class is an object? u An object is an instance of a class? u “Then, what is the class of a class? u The 56 metaclass

Meta class u. A meta class is the class of a class. u The attributes of a meta class can be used to describe a class (e. g. # of instances of a class). 57

Meta class u Explicit support of meta classes means that objects, classes and meta classes are treated uniformly. u Classes can be created at run-time by explicitly sending a message to a special metaclass. 58

Metaclass u Metaclasses are hidden from the user. u A metaclass hierarchy is maintained parallel to the class hierarchy. 59

Metaclass u 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. 60

Readings u Chapter 61 2 Section 2. 1
- Slides: 61