Presentation is loading. Please wait.

Presentation is loading. Please wait.

The Class Concept Abstraction What is a class? Two parts of the class

Similar presentations


Presentation on theme: "The Class Concept Abstraction What is a class? Two parts of the class"— Presentation transcript:

1 The Class Concept Abstraction What is a class? Two parts of the class
Two views of the class Class vs. type Prof. Lorenz

2 A Class -- Abstraction Over Objects
A class represents a set of objects that share a common structure and a common behavior. NU

3 Class = Abstraction Over Objects
Phenomena: Similar Objects Abstraction Mechanism: Class Basic Metaphor: Data Type An Abstraction Process NU

4 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

5 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

6 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

7 ObjectGraph: in UML notation
Route1:BusRoute :BusList buses busStops :BusStopList Bus15:Bus passengers CentralSquare:BusStop waiting :PersonList :PersonList Joan:Person Paul:Person Seema:Person Eric:Person NU

8 Shared vs. Particular Features
NU

9 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

10 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

11 Java Interface ClassGraphI
Collection getIncomingEdges(Object v) A List of edges (EdgeI objects) coming into node v. Object getNode(String l) The node labeled l in the class graph. Collection getNodes() A collection of nodes in the class graph. Collection getOutgoingEdges(Object v) A collection of edges (EdgeI objects) going out of node v. NU

12 UML class graph H f F g G D E e A B C NU

13 Java: how to use the Interface
public class ClassGraph extends Object implements ClassGraphI NU

14 Java Interface EdgeI String getLabel() The label of the edge, or null if it is not a construction edge. Object getSource() The source node of the edge. Object getTarget() 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

15 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

16 The Two Parts of a Class Static Part Dynamic Part Implementation
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 Implementation Instance Variables --- Interface --- Messages & Methods NU

17 Views and Parts in C++ Static Part Dynamic Part Implementation
Kinds of Interfaces in C++ Users of a Class: Instances Subclasses Clients Levels of Visibility: private protected public Static Part Dynamic Part Implementation Interface private data members private function members public data members public function members NU

18 Public Data Members? class Person { public age int; } private a int;
public int age() {return a;} class Person{ public int age() {return current_year-birth_year;} AVOID INTERFACE CHANGES NU

19 Views and Parts in Eiffel
Level and direction of export are orthogonal to kind of feature. User cannot know the kind of implementation of a feature. Static Part Dynamic Part Implementation Interface Unexported attributes Unexported routines Exported without args? Exported routines NU

20 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: Boolean type 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

21 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

22 Inheritance Sets, Objects and Inheritance
Specialization and Factorization Basic Terminology and Notation Inheritance Hierarchies NU

23 Inheritance -- What does it look like?
NU

24 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

25 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

26 Program Domain Example
Shape Location Rotation Observe the OMT (Object Modeling Technique) style of using a triangle for denoting Inheritance Move Locate Rotate Rectangle Draw Ellipse Draw NU

27 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) the same accelerate method. Classification of hierarchies: Connected / Disconnected Tree / DAG NU

28 Terminology: Smalltalk vs. 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

29 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 member in C++ (Inspector). NU

30 Typing and Strict Inheritance
Value, Type, Variable Static and Dynamic Typing Strict Inheritance NU

31 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

32 ObjectGraph: in UML notation A value
Route1:BusRoute :BusList buses busStops :BusStopList Bus15:Bus passengers CentralSquare:BusStop waiting :PersonList :PersonList Joan:Person Paul:Person Seema:Person Eric:Person NU

33 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

34 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

35 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

36 “Nineteen-eighty-four”
Dynamic Typing Type is associated with values. Each value carries a tag, identifying its type. A variable may contain any value of any type. MyBook “Nineteen-eighty-four” string 1984 Integer NU

37 Strong Typing -- What does it look like?
Strong typing prevents mixing abstractions. NU

38 Static Typing (is Strong Typing)
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. Identifier Type NU

39 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

40 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

41 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

42 Rights and obligations
Precondition binds clients Postcondition binds class NU

43 Example NU

44 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

45 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

46 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

47 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

48 Class invariants and class correctness
A class invariant only applies to public methods; private methods are not required to maintain the invariant. NU

49 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

50 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

51 Invariant Rule The class invariant is implicitly added (anded) to both the precondition and postcondition of every exported routine Could do, in principle, without class invariants. But they give valuable information. Class invariant acts as control on evolution of class A class invariant applies to all contracts between a method of the class and a client NU

52 --Any allocated resource must have the required facilities
Resource Allocation <JobCategory> reqs <Facility> 0..* type provides 0..* <Job> when: TimeInterval schedule allocated <Resource> 0..* 0..1 inv Job::allocated<>0 ==> allocated.provides->includesAll(type.reqs) --Any allocated resource must have the required facilities inv Resource::jo1, jo2: Job:: (schedule->includesAll({jo1,jo2}) ==> jo1.when.noOverlap(jo2.when) -- no double-booking of resources NU

53 Benefits of Strong Typing
Enforce the design decisions. Prevent runtime crashes: Mismatch in # of parameters Mismatch in parameters Sending an object an inappropriate message Early error detection reduces: Development time Cost Effort Type declarations help to document programs X: speed; (* Good *) Y: real; (* Bad *) Z = 3; (* Worse *) More efficient and more compact object code type SMALL_COUNTER is range ; NU

54 Benefits of Strong Typing
class A { Object b; Object c; } class B { Object d; class C extends B { Object b c d A D B C If all instance variables are of class Object we get strange class graphs NU

55 Benefits of Strong Typing
class A { B b; C c; } class B { D d; class C extends B { Object c A D b B C d NU

56 Strict Inheritance Extension of base class:
Structure Protocol Behavior Engineer and SalesPerson extend, each in its own way, the structure and protocol of Employee. Identifying the Employee abstraction, helps us define more types: General Idea: similar to procedure call, but applied to data. If procedure P calls procedure Q, then it can be said that “P extends Q” P does everything that Q does + more. struct Manager: public Employee { char *degrees; // ... }; NU

57 Is-A Relationship Inheritance represents an is a relationship.
A subclass is a (more specialized) version of the base class: Manager is an Employee. Rectangle is a Shape. A function taking the class B as an argument, will also accept a class D derived from B. class Monom { ... }; Monom operator +(Monom m1, Monom m2) { } class DMonom: public Monom { ... } d1, d2; Monom m = d1 + d2; NU

58 Types and OOP Types and Classes Subtypes and Subclasses
Types: Administrative aid Check for typos. Type predicates and type calculus. Classes: A mould for creating objects Usually, type = class. Subtypes and Subclasses Subtype: a type which is a subset of another type. Subclass: a class that inherits from another class. Extend the mould. Usually, the subtype and subclass relationship are isomorphic. Strict inheritance and Subtypes: With strict inheritance, we have full conformance and substitutability, and therefore, a subclass is always a subtype. NU

59 Properties of Strict Inheritance
The structure and the behavior of a subclass are a superset of those of the superclass. The only kind of inheritance in Oberon (the grand-daughter of Pascal). Conformance (AKA substitutability) If a class B inherits from another class A, then the objects of B can be used wherever the objects of A are used. Benefits of strict inheritance: New abstraction mechanism: extend a given class without touching its code. No performance penalty. Compile-time creature. Can be thought of as a syntactic sugar which helps define classes. No conceptual penalty. Structured path for understanding the classes. Drawbacks of strict inheritance: Not overly powerful! Except in the total size of objects, which, due to alignment, depends on the depth of inheritance hierarchy NU

60 Collections in Little Smalltalk
What are they? Kinds of collections. Basic Operations. Usage of Inheritance in the Collections Library. Roman numbers example. The Stack Example: Defining a new kind of collection. NU

61 What are Collections? Collections provide the means for managing and manipulating groups of objects. Kinds of collections: Set: represents an unordered group of objects. Elements are added and removed by value. Dictionary: is also an unordered collection of elements, but insertions and removals require an explicit key. Interval: represents a sequence of numbers in arithmetic progression, either ascending or descending. List: is a group of objects having a specific linear ordering. Insertions and removals are done in the extremes. Array: a fixed-size collections. Elements can not be inserted or removed, but they may be overwritten. String: can be considered to be a special form of Array, where the elements must be characters. Collections can be converted into a different kind by the use of messages like asSet, asArray, etc. NU

62 Classification of Collections
The different kinds of Collections may be classified according to several attributes. Size Fixed Unbounded Ordering Ordered Unordered Access Method By value Indexed Sequential Choose the right Collection by examining its attributes. NU

63 Collections’ Attributes
Name Creation Fixed Order? Insertion Access Removal Method Size? Method Method Method Set new no no add: includes: remove: Dictionary new no no at:put: at: removeKey: Interval n to: m yes yes none none none List new no yes addFirst: first removeFirst addLast: remove: Array new: yes yes at:put: at: none String new: yes yes at:put: at: none This is rarely a problem, since one usually creates strings as literals. Note however that the implementation of new: in the class String is buggy. It creates a string of size 0! NU

64 Inserting an Element Indexed collections (Dictionary, Array) require an explicit key and a value, by using the method at:put: > D <- Dictionary new at:'com1204' put:'OOP'; \ at:'com3230' put:'OOD'; at:'com3351' put:'PPL' Dictionary ( 'com1204' 'com3230' 'com3351' ) Non-indexed collections require only a value, by using the method add: > S <- Set new add:'red'; add:'green'; add:'blue' Set ( 'blue' 'green' 'red' ) In the case of Lists the values can be added in the beginning or end of the collection, by using the methods addFirst: and addLast: > L <- List new addLast: 'End'; addFirst: 'Begin' List ( 'Begin' 'End' ) NU

65 Removing an Element In indexed collections the removal method requires the key. > D removeKey: 'com1204' Dictionary ( 'com3230' 'com3351' ) In collections with fixed size (Array and String) elements can not be removed. In non-indexed collections the argument is the object to be removed. > S remove: 'green' Set ( 'blue' 'red' ) In a List, an element can be removed from the beginning (removeFirst) or by value (remove:). > L removeFirst remove: 'END' List ( ) NU

66 Accessing an Element In indexed collections the elements are accessed by key. > 'SmallTalk' at: 6 $T The method keys returns the keys of an indexed collection. > D keys Set ('com3230' 'com3351') In non-indexed collections we already have the value, hence the only question is whether it is in the collection. > S includes: 'black' false The method includes: is defined for all collections. > #( ) keys includes: 5 true NU

67 Selecting Elements The method select: returns a collection containing all the elements that satisfy some condition. It receives a one-argument block that is evaluated for each element in the collection, returning true or false. The returned collection is of the same class as the receiver in case it is Set, List, and Array, and Array otherwise. > #( ) select: [ :i | ( i rem: 2 ) = 0 ] Array ( 2 4 ) The method reject: returns the complementary collection. > #( ) asSet reject: [ :i | ( i rem: 2 ) = 0 ] Set ( ) Strings are special: > ' ' select: [ :c | c > $5 ] Array ( $6 $7 $8 $9 ) NU

68 Performing Computations
The method do: allows a computation to be performed on every element in a collection. It also receives a one-argument block. > B <- [ :x | ( x rem: 2 ) = 0 ifTrue: [ ( x printString , ' is even!' ) print ] \ ifFalse: [ ( x printString , ' is odd!' ) print ] ] Block > #( ) do: B 1 is odd! 2 is even! 3 is odd! 4 is even! 5 is odd! Array ( ) NU

69 Collecting Results The method collect: is similar to do:, but it produces a new collection containing the results of the block evaluation for each element of the receiver collection. > #( ) collect: [ :i | i factorial ] Array ( ) > #( ) collect: [ :j | j rem: 2 ] Array ( ) > D <- Dictionary new at:0 put:'even'; at:1 put:'odd' Dictionary ( 'even' 'odd' ) > #( ) collect: [ :x | D at: ( x rem: 2 ) ] Array ( 'odd' 'even' 'odd' 'even' 'odd' ) > factor <- 1.1 1.1 > grades <- #( ) collect: [ :g | g * factor ] Array ( ) NU

70 Accumulative Processing
The method inject:into: is useful for processing all the values of a collection and returning a single result. The first argument is the initial value, and the second is a two-parameter block that performs some computation. At each iteration the block receives the result of the previous computation and the next value in the collection. > A <- #( ) Array ( ) > ( A inject:0 into: [:a :b| a + b ] ) / A size 3 “average of the values in the array” > A inject:0 into: [:x :y| x > y ifTrue:[x] ifFalse:[y]] 5 “maximum value in the array” > A inject:0 into: [:i :j| ( j rem: 2 ) = 0 \ ifTrue: [ i + 1 ] ifFalse: [ i ] ] 2 “number of even values in the array” NU

71 Implementation Examples
Collection inject:into: inject: aValue into: aBlock | last | last <- aValue. self do: [:x | last <- aBlock value:last value:x ]. ^last Collection size size ^self inject: 0 into: [ :x :y | x + 1 ] Collection occurrencesOf: occurrencesOf: anObject ^self inject: 0 into: [ :x :y | ( y = anObject ) ifTrue: [ x + 1 ] ifFalse: [ x ] ] NU

72 Roman Numbers Class Roman Object dict Methods Roman 'all' new
dict <- Dictionary new at:1 put: 'I'; at: 4 put: 'IV'; at: 5 put: 'V'; at: 9 put: 'IX'; at: 10 put:'X'; at: 40 put: 'XL'; at: 50 put: 'L'; at: 90 put: 'XC'; at: 100 put: 'C'; at: 400 put: 'CD'; at: 500 put: 'D'; at: 900 put: 'CM'; at: 1000 put: 'M' | generate: anInteger | count roman | count <- anInteger. roman <- ''. ( dict keys select: [ :k | k <= count ] ) sort reverseDo: [ :key | ( count quo: key ) timesRepeat: [ roman <- roman , ( dict at: key ) ]. count <- count rem: key ]. ^roman ] NU

73 The Class Stack A Stack is composed by a List. Class Stack Object list
Methods Stack new list <- List new | push: anObject list addFirst: anObject pop | top | top <- list first. list removeFirst. ^top size ^list size do: aBlock list do: aBlock ] A Stack is composed by a List. NU


Download ppt "The Class Concept Abstraction What is a class? Two parts of the class"

Similar presentations


Ads by Google