740 likes | 905 Views
The Class Concept. Abstraction What is a class? Two parts of the class Two views of the class Class vs. type. A Class -- Abstraction Over Objects. A class represents a set of objects that share a common structure and a common behavior. Class = Abstraction Over Objects.
E N D
The Class Concept Abstraction What is a class? Two parts of the class Two views of the class Class vs. type Prof. Lorenz
A Class -- Abstraction Over Objects A class represents a set of objects that share a common structure and a common behavior. NU
Class = Abstraction Over Objects • Phenomena: Similar Objects • Abstraction Mechanism: Class • Basic Metaphor: Data Type An Abstraction Process NU
Dimensions of the Class Concept • Static vs. Dynamic Aspects • Shared vs. Particular features • Internal vs. External views • Multiple Interfaces • The Data Type Metaphor • Relationship with Instances • Class as an instance factory • Existence as an Object • Meta classes NU
What is a Class? • Abstraction Over Objects: a set of objects that share: • Dynamic Aspect • Protocol: Declarations (signatures) of function members in C++ • Behavior: Definitions (body) of function members in C++ • Static Aspect • Structure: Declarations of data members in C++. • But not the definitions (value) of data members. • State is not part of the class abstraction. • Mould for objects: used to instantiate objects (instances) with distinct identities that share protocol, behavior and structure but may assume different states. • In contrast to concrete object, a class does not necessarily exist in (run) time and (memory) space. • What’s not a Class? • An object is not a class, but a class may be an object. • In “exemplar based’’ languages, there are no classes. New objects are “instantiated” from existing objects. • Not every set of objects is a class NU
Collaborating Classes: UML find all persons waiting at any bus stop on a bus route busStops BusRoute BusStopList OO solution: one method for each red class buses 0..* BusStop BusList waiting 0..* passengers Bus PersonList Static aspect Dynamic aspect Person 0..* NU
ObjectGraph: in UML notation :BusList Route1:BusRoute buses busStops :BusStopList Bus15:Bus passengers CentralSquare:BusStop waiting :PersonList :PersonList Joan:Person Paul:Person Seema:Person Eric:Person NU
A Different Abstraction over Objects • Common Parts: • Structure • Protocol • Specified per Instance: • State: values of data members. • Behavior: “values” of function members. class Stack {enum { N = 100 };int buff[N];int size;public:void (*push)(int element);int (*pop)(void); }; Abstraction, but not of the desired nature! NU
The Two Views of a Class • Implementation: the common structure and the details of how the behavior works. • Body in Ada • Definitions of function members in C++ • Interface: the common protocol and the external specifications of the behavior. • Specification in Ada • Declarations in C++ • Interface as a Contract: defines the contract of the relationship between instances of the class and their clients. • Strongly typed languages can detect some contract violations prior to run time. • Interface Components: • Declaration of all class operations • Declarations of externally accessible attributes • Other pertinent declarations: constants, exceptions and other classes and/or types, etc. • Multiple Interfaces: frequently, the class has different interfaces to different kinds of clients. • Example: electronic mail agent has different interfaces to users and to administrators. NU
Java Interface ClassGraphI • CollectiongetIncomingEdges(Object v) A List of edges (EdgeI objects) coming into node v. • ObjectgetNode(String l) The node labeled l in the class graph. • CollectiongetNodes() A collection of nodes in the class graph. • CollectiongetOutgoingEdges(Object v) A collection of edges (EdgeI objects) going out of node v. NU
UML class graph H f F g G D E e A B C NU
Java: how to use the Interface • public class ClassGraph extends Object implements ClassGraphI NU
Java Interface EdgeI • StringgetLabel() The label of the edge, or null if it is not a construction edge. • ObjectgetSource() The source node of the edge. • ObjectgetTarget() The target node of the edge. • boolean isConstructionEdge() Is the edge a construction (part) edge? • boolean isInheritanceEdge() Is the edge an inheritance (superclass) edge? NU
Implementation in the Interface? • In C++, the structure of an instance is defined in the private part of class interface. • Give away state information • Changes to representation -> a functional affect on clients. • Why isn’t the structure of an instance part of the Implementation? • Needed by the compiler. • Cannot allocate memory for objects without knowing their size. • Size is determined by structure. • Alternatives: • OO Hardware: technology is not sufficiently advanced. • Sophisticated Compilers: slowly, but coming. • Other OOPLs: not as sexy as C++ and Java. NU
The Two Parts of a Class • Dynamic Part: specifications of the dynamic aspects of the class instances. • Static Part: specifications of the static aspects of the class instances. • Example: views and parts in Smalltalk. Static Part Dynamic Part Instance Variables --- Implementation Interface --- Messages &Methods NU
Views and Parts in C++ Implementation Interface • Kinds of Interfaces in C++ • Users of a Class: Instances Subclasses Clients • Levels of Visibility: private protected public Dynamic Part Static Part private data members private function members public function members public data members NU
Public Data Members? class Person { public age int; } class Person { private a int; public int age() {return a;} } class Person{ public int age() {return current_year-birth_year;} } AVOID INTERFACE CHANGES NU
Views and Parts in Eiffel Implementation Interface • Level and direction of export are orthogonal to kind of feature. • User cannot know the kind ofimplementation of a feature. Dynamic Part Static Part Unexported attributes Unexported routines Exported routines Exported without args? NU
Abstract Data Types and Classes • Type: A set of values with common operations • Main Application: protect mixing unrelated values/operations • Example 1: Decree forbidding pointers multiplication • Example 2: Decree against assigning a struct to an int variable • Abstract Data Type: defined by the set of basic values, means of generating other values, set of allowed operations and their meaning. • Example: Booleantype in Pascal. • Values: True, False. • Operations: Not, And, Or, =,<>,<=,>=,<,>. • Implicit Operations: Assignment, argument passing, function return value. Conversion to integer (ord). • Class: A lingual mechanism that gives the means for realization of a: • Type • Abstract Data Type • Abstraction NU
User Defined Types • If a user-defined type is to be a first class citizen (have the look and feel of a built-in type), then the programming language must provide the ability to define for it: • Initialization • Memory management: • Allocation • Deallocation • Type conversions • Literals (basic values) • A set of operators • Operator overloading NU
Inheritance • Sets, Objects and Inheritance • Specialization and Factorization • Basic Terminology and Notation • Inheritance Hierarchies NU
The Personnel Example • Suppose we want to computerize our personnel records... • We start by identifying the two main types of employees we have: • struct Engineer { • Engineer *next; • char *name; • short year_born; • short department; • int salary; • char *degrees; • void raise_salary(int how_much ); • // ... • }; • struct SalesPerson { • SalesPerson *next; • char *name; • short year_born; • short department; • int salary; • float *commission_rate; • void raise_salary(int how_much ); • // ... • }; NU
Factorization and Specialization struct Employee { char *name; short year_born; short department; int salary; Employee *next; void raise_salary(int how_much ); // ... }; C version:struct Engineer {struct Employee E;char *degree; /* ... */ }; Indeed, inclusion is a poor man’s (poor) imitation of inheritance! struct Engineer: Employee { char *degrees; // ... }; struct SalesPerson: Employee { float *commission_rate; // ... }; NU
Program Domain Example Rectangle Ellipse Draw Draw Shape Location Rotation Observe the OMT (Object Modeling Technique) style ofusing a triangle for denoting Inheritance Move Locate Rotate NU
Inheritance Hierarchy Vehicle Observe the direction of the arrows! Air Vehicle Land Vehicle Water Vehicle Car Truck Boat Submarine Airplane Rocket • Fundamental Rule: • Suppose that a Vehicle has a • speed attribute, and • an accelerate method, • then all other classes in the above diagram will have (at least) • speed attribute, and • the same accelerate method. • Classification of hierarchies: • Connected / Disconnected • Tree / DAG NU
Terminology: Smalltalk vs. C++ Smalltalk C++ Inherit Superclass Subclass Instance Variable Method Message Class Variable Class Method Inherit/Derive Base class Derived class Data Member Member function Member function call Static data member Static function member NU
The Eiffel Terminology • Inheritance: • Heir: immediate subclass. • Descendant: transitive closure of the heir relation. • Proper Descendant: Descendant minus heir. • Parent: immediate super-class. • Ancestor: transitive closure of the parent relation. • Proper Ancestor: Ancestor minus parent. • Taxonomy of features: • Feature: member in C++. • Attribute: data member of C++. • Routine (Service): function member in C++. • Procedure (Command): void function member in C++ (Mutator). • Function (Query): ordinary function memberin C++ (Inspector). NU
Typing and Strict Inheritance • Value, Type, Variable • Static and Dynamic Typing • Strict Inheritance NU
Value, Type, Variable • Value - the entities manipulated by programs. • Contents of a memory cell at a specific moment. • State of an object. • Type - means of classification of values. • Type is a set of values that have similar protocol. • Protocol - collection of permissible operations. • Variable • A name of a memory cell that may contain values. NU
ObjectGraph: in UML notationA value :BusList Route1:BusRoute buses busStops :BusStopList Bus15:Bus passengers CentralSquare:BusStop waiting :PersonList :PersonList Joan:Person Paul:Person Seema:Person Eric:Person NU
Significance of Type • Type Determines Meaning:What will be executed as a result of the following expression?a + b • Integer addition, if a and b are integer, or • Floating point addition, if a and b are of floating point type, or • Conversion to a common type and then addition, if a and b are of different types. • Type determines what’s allowed: Is the following expression legal?X[i] • Yes, if X of an array type and i is of an integral type. • No, e.g., if X is a real number and i is a function. NU
Loopholes in the Type System Types usually hide the fact that a variable is just a box of bits, however: Type Casting, as in long i, j, *p = &i, *q = &j; long ij = ((long) p) ^ ((long) q)); and union (variable records), as in union { float f; long l; } d; d.f = 3.7; printf("%ld\n", d.l); allow one to peep into the implementation of types. NU
Typing in Languages • Formal Lang.: classified by significance of type • Strongly typed languages: a type is associated with each value. It is impossible to break this association within the framework of the language. • ML, Eiffel, Modula, ... • Weakly typed languages: values have associated types, but it is possible for the programmer to break or ignore this association. • C, Turbo-Pascal • Untyped languages: values have no associated type. • Assembly, BCPL, Lisp, Mathematica, Mathematical formulae. • Programming Lang.: classified by time of enforcement • Dynamic typing: type rules are enforced at run-time. Variables have no associated type. • Smalltalk, Prolog, ... • Static typing: type rules are enforced at compile time. All variables have an associated type. • C, Pascal, Eiffel, ML, ... NU
Dynamic Typing MyBook 1984 “Nineteen-eighty-four” string Integer • Type is associated with values. Each value carries a tag, identifying its type. • A variable may contain any value of any type. NU
Strong Typing -- What does it look like? Strong typing prevents mixing abstractions. NU
Static Typing (is Strong Typing) Type Identifier • In static typing, each variable, and even more generally, each identifier is associated with a type. • This usually means that all identifiers should be declared before used. However this is not always the case: • Type inference in ML. • Implicit type inference in Fortran. • Grammatical type inference in some dialects of Basic. • A variable may contain only values of its associated type. • All expressions are guaranteed to be type-consistent: • No value will be subject to operations it does not recognize. • This allows the compiler to engage in massive optimization. • Static typing goes together with strong typing: • The two terms are used almost synonymously in the literature and in this course. • In OOP, the preferred term is strong typing, since, as we will see later, there is also a notion of dynamic type even in statically/strongly typed systems. NU
Why Static Typing? • Recursive functions theory teaches us that an automatic tool is very limited as a programming aid • Cannot determine if the program stops. • Cannot determine if the program is correct. • Cannot decide almost any other interesting run time property of a program. • One thing that can be done automatically is make sure that no run time type error occurs. • We can use every tiny bit of help in our struggle against the complexity of software! • Few other automatic aids are: • Garbage collection • Const correctness • Pre and post conditions NU
Design by contract • Object-Oriented Software Construction by Bertrand Meyer, Prentice Hall • The presence of a precondition or postcondition in a routine is viewed as a contract. NU
Rights and obligations • Parties in the contract: class and clients • require pre, ensure post with method r: If you promise to call r with pre satisfied then I, in return, promise to deliver a final state in which post is satisfied. • Contract: entails benefits and obligations for both parties NU
Rights and obligations • Precondition binds clients • Postcondition binds class NU
Example NU
If precondition is not satisfied • If client’s part of the contract is not fulfilled, class can do what it pleases: return any value, loop indefinitely, terminate in some wild way. • Advantage of convention: simplifies significantly the programming style. NU
Source of complexity • Does data passed to a method satisfy requirement for correct processing? • Problem: no checking at all or: multiple checking. • Multiple checking: conceptual pollution: redundancy; complicates maintenance • Recommended approach: use preconditions NU
Class invariants and class correctness • Preconditions and postconditions describe properties of individual methods • Need for global properties of instances which must be preserved by all routines • 0<=nb_elements; nb_elements<=max_size • empty=(nb_elements=0); NU
Class invariants and class correctness • A class invariant is an assertion appearing in the invariant clause of the class. • Must be satisfied by all instances of the class at all “stable” times (instance in stable state): • on instance creation • before and after every remote call to a routine (may be violated during call) NU
Class invariants and class correctness • A class invariant only applies to public methods; private methods are not required to maintain the invariant. NU
Invariant Rule • An assertion I is a correct class invariant for a class C iff the following two conditions hold: • The constructor of C, when applied to arguments satisfying the constructor’s precondition in a state where the attributes have their default values, yields a state satisfying I. • Every public method of the class, when applied to arguments and a state satisfying both I and the method’s precondition, yields a state satisfying I. NU
Invariant Rule • Precondition of a method may involve the initial state and the arguments • Postcondition of a method may only involve the final state, the initial state (through old) and in the case of a function, the returned value. • The class invariant may only involve the state NU