610 likes | 727 Views
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. Contents. Objects Messages Classifications Classes Instances Metaclasses. Object-based Programming.
E N D
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.
Contents • Objects • Messages • Classifications • Classes • Instances • Metaclasses
Object-based Programming • One way to view the world is as a collection of autonomous, interacting objects. • Examples: people, animals, plants, buildings, rooms, stairs, ...
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
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
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
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
Examples • A computer • Autonomous: it can do many things • Communicative (with people, with other computers) • A serial No. • Built/Destroyed
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.
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.
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
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.
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
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)
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.
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.
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.
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.
Again, Examples of objects A person: • Operations: • Eat • Walk • Work • … ID: SSN • States: • Name • Sex • Age • Interface: • What is in a person’s resume…
Examples of objects • A book • Operations • Buy • Open • Get info • Close • Discard • ID: ISBN • States: • Title • Author • Publisher • Interface • All the above operation names
Properties of Objects • Encapsulation (Data & Operations) • Information Hiding • Data Abstraction (with classes) • Abstract Data Type (with classes)
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
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).
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.
Classification Animal Mammal Bird People . . . . . Dog man woman John Jane
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.
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."
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)
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.
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.
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.
What is a Class • A class is a user-defined type. • Booch: • “A set of objects that share a common structure and common behavior”
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.
A class(Similar to C++) class Integer { Ds: int I Ops: setValue(int n) Integer addValue(Integer j) }
Examples of class • class horse{ • Ds: • Age • Weight • Color • Ops: • Drag • Run • ride • }
Examples of class • class building{ • Ds: • Name • Architecture • Height • Time built • Builder • Ops: • Open • Enter • Leave • … • }
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.
Instantiation • The mechanism of creating new objects from a class definition is called instantiation. • Every class has such a mechanism.
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.
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
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.
Instantiation Examples • bk = new Book ( Actually in the Publishing House); • bldg = new Building ( Actually by workers) • child = new Person ( Actually by parents)
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
ex3class.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 ; } ;
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 ) ;}
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 }
ex3class.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 ; } ;
ex3class.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 * r ) ;} double Circle:: circumference( void ) const { return( 2 * PI * r ) ;}
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 ) ; }
ex3class.cpp void 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 ; }