COSC 2767 ObjectOriented Programming Haibin Zhu Ph D
COSC 2767: Object-Oriented Programming Haibin Zhu, Ph. D. Professor of Computer Science, Nipissing University 1
Lecture 3 Messages, Instances, and Inheritances 2
Messages are not Function Calls u Recall from chapter 1 that we noted the following differences between a message and a function (or procedure) call u A message is always given to some object, called the receiver u The action performed in response is determined by the receiver, different receivers can do different actions in response to the same message. 3
Message Passing Syntax u Although the syntax may differ in different languages, all messages have three identifiable parts: a. Game. display. Card (a. Card, 42, 27); u The message receiver u The message selector u An optional list of arguments 4
Statically Typed and Dynamically Typed Languages u A distinction we will see throughout the term is between the following: u A statically typed language requires the programmer to declare a type for each variable. The validity of a message passing expression will be checked at compile time, based on the declared type of the receiver. u A dynamically typed language associates types with values, not with variables. A variable is just a name. The legality of a message cannot be determined until run-time. 5
The Receiver Variable u u u 6 Inside a method, the receiver can be accessed by means of a pseudo-variable Called this in Java, C++, C# Called self in Smalltalk, Objective-C, Object Pascal Called current in Eiffel function Playing. Card. color : colors; begin if (self. suit = Heart) or (self. suit = Diamond) then color : = Red else color : = Black; end
Implicit Use of This u u u 7 Within a method a message expression or a data access with no explicit receiver is implicitly assumed to refer to this: class Playing. Card {. . . public void flip () { set. Face. Up( ! face. Up ); }. . . } Is assumed to be equivalent to: class Playing. Card {. . . public void flip () { this. set. Face. Up( ! this. face. Up); }. . . }
Object Creation u In most programming languages objects must be created dynamically, usually using the new operator: u Playing. Card a. Card; u // simply names a new variable u a. Card = new Playing. Card(Diamond, 3); u // creates the new object u The declaration simply names a variable, the new operator is needed to create the new object value. 8
Memory Recovery u Because in most languages objects are dynamically allocated, they must be recovered at run-time. There are two broad approaches to this: u Force the programmer to explicitly say when a value is no longer being used: u delete a. Card; // C++ example u Use a garbage collection system that will automatically determine when values are no longer being used, and recover the memory. 9
Memory Errors u u u u u 10 Garbage collection systems impose a run-time overhead, but prevent a number of potential memory errors: Running out of memory because the programmer forgot to free values Using a memory value after it has been recovered Playing. Card * a. Card = new Playing. Card(Spade, 1); delete a. Card; cout << a. Card. rank(); Free the same value twice Playing. Card * a. Card = new Playing. Card(Spade, 1); delete a. Card; // delete already deleted value
Instantiation u The mechanism of creating new objects from a class definition is called instantiation mechanism. u Every class has such a mechanism. 11
Instantiation u. Static instantiation and Dynamic instantiation. uinstantiation at compile time; uinstantiation at run time. u Dynamic instantiation requires a run time support for allocation and deallocation of memory. 12
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 u In Smalltalk, classes are also objects u See Metaclass 13
A Definition for Object u Object : : = <n, c, s>, where u n is the identification or name of the object; u c is the identification or name of the class of this object; u s is the actual space for memory; u Note: the operations of the object is implemented in the class. 14
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) u North. Bay = new City (Actually by the immigrants in 18 XX? ) 15
About the formula u If you really understand the formula about object and class, it is easy for you to understand the objects(instances), classes, and instantiation of C++. u Class : : =<n, d, m, x>; u Object : : = < n, c, s >. 16
Constructors u u u 17 A constructor is a function that is implicitly invoked when a new object is created. The constructor performs whatever actions are necessary in order to initialize the object. In C++, Java, C# a constructor is a function with the same name as the class. In Python constructors are all named __init__ In Delphi, Objective-C, constructors have special syntax, but can be named anything. (Naming your constructors create is a common convention). class Playing. Card { // a Java constructor public Playing. Card (int s, int r) { suit = s; rank = r; face. Up = true; }. . . }
Overloaded Constructors u u u u 18 Constructors are often overloaded, meaning there a number of functions with the same name. They are differentiated by the type signature, and the arguments used in the function call or declaration: class Playing. Card { public: Playing. Card ( ) // default constructor, used when no arguments are //given { suit = Diamond; rank = 1; face. Up = true; } Playing. Card (Suit is) // constructor with one argument { suit = is; rank = 1; face. Up = true; } Playing. Card (Suit is, int ir) // constructor with two arguments { suit = is; rank = ir; face. Up = true; } }; Playing. Card *card. One = new Playing. Card(); Playing. Card *card. Two = new Playing. Card(Heart); Playing. Card *card. Three = new Playing. Card(Diamond, 7);
Metaclasses u In Smalltalk (and Objective-C) classes are just objects, instances of class Class. “new” is just a message given to a class object. If we want to create constructors, where do we put them? u They can't be part of the collection of messages of instances of the class, since we don't yet have an instance. u They can't be part of the messages understood by class Class, since not all classes have the same constructor message. u Where do we put the behavior for individual class instances? 19
Solution: Create New Classes for Classes u The solution is to create a new class, whose only instance is itself a class. u An elegant solution that maintains the simple instance/class relationship. 20
Smalltalk Metaclass 21
Understanding Instantiation (Optional thinking, not required) u What is the class of all the human beings? u The Nature? u What is the instantiation of a person? u Who creates a new-born child? Who sends the create message? To whom the message be sent ? u The Parents? The Nature? 22
Inheritance 1. 2. 3. 4. 5. 6. 23 Classification Sharing Inheritance Subclass The Categories of Inheritance Abstract Class
Classification u An object can be "of" a certain class not its creator. u An apple is of Fruit, but is not the instance of Fruit. u In this view, classes are like sets. u John is a man. Mary is a woman. u Bob is a dog. u All men are people. All women are people. u All people are mammals. All dogs are mammals. 24
Classification/Inheritance Animal Classification Mammal People man John 25 Dog woman Mary Bird. . . Inheritance Instantiation
Classification u Classification arises from the universal need to describe uniformities of collections of instances. u Classification is a basic idea for understanding the concept inheritance 26
Classification/Inheritance u. Commonality u. The base class captures the common information (attributes) and features (operations) of the derived classes. 27
Classification/Inheritance u Customization u An existing class is used to create a customized version of the class. u Common Design Interface u A base class may define the design requirements for its derived classes by specifying a set of member functions that are required to be provided by each of its derived classes. 28
The is-a Rule u Our idealization of inheritance is captured in a simple rule-of-thumb. u Try forming the English sentences ``An A is-a B''. If it ``sounds right'' to your ear, then A can be made a subclass of B. u A dog is-a mammal, and therefore dog inherits from mammal u That a car is-a(n) engine sounds wrong, and therefore inheritance is not natural. but a car has-a(n) engine. 29
Sharing u The sharing is important in object-orientation. u Inheritance is the technique to realize sharing. u Inheritance means that new classes can be derived from existing classes. u The subclass inherits the attributes and the operations of the superclass(base class) but the subclass(derived class) can define additional operations and attributes. 30
Sharing u This mechanism can be taken specialization mechanism. u Instances of a subclass are specializations (additional state and behavior) of the instances of the superclass. u This mechanism also can be taken as generalization mechanism. u Instances of the superclass generalize (restrict) the instances of the subclasses. 31
Sharing u. Sharing is also the basic idea of inheritance. u. The ability of one class to share the behavior of another class without explicit redefinition. u. An approach which allows classes to be created based on a old class. 32
An Argument for Substitution u u u 33 Instances of the subclass must possess all data areas associated with the parent class. Instances of the subclass must implement, through inheritance at least (if not explicitly overridden) all functionality defined for the parent class. (They can also define new functionality, but that is unimportant for the present argument). Thus, an instance of a child class can mimic the behavior of the parent class. It therefore seems reasonable that a variable declared as a parent, should be able to hold a value generated from the child class.
Practical Meaning of Inheritance Data members in the parent are part of the child u Behavior defined in the parent are part of the child u Note that private aspects of the parent are part of the child, but are not accessible within the child class. u Reusing the existing design reduces software development and testing costs. u A new class obtains the data members and member functions of an existing class. u 34
Inheritance is both Extension and Contraction u u u 35 Because the behavior of a child class is strictly larger than the behavior of the parent, the child is an extension of the parent. (larger) Because the child can override behavior to make it fit a specialized situation, the child is a contraction of the parent. (smaller) This interplay between inheritance and overriding, extension and contraction, is what allows objectoriented systems to take very general tools and specialize them for specific projects. This interplay is ultimately the source of a great deal of the power of OOP.
Understand Inheritance u. Imaginary goal: write a new class Dog. u. Don't start from scratch if a very similar class, e. g. Mammal, already exists. u. Inherit from an existing class instead. Terminology: Dog inherits from Mammal, Mammal is the superclass and Dog is the subclass. 36
Inheritance: conceptually u ”Automatically copy-and-paste" whenever superclass (Mammal) changes. u Only need to declare "inherit Dog from Mammal" u Declare what new instances Dog has (gets all Mammal instances automatically) u Write new methods u Override some existing methods u means when pasting, don't paste this one in. 37
What is Inheritance? Inheritance is a mechanism for expressing similarity. 2. Inheritance is the natural property of classification. 3. Inheritance is the mechanism which allows a class A to inherit properties of a class B. We say ``A inherits from B''. Objects of class A thus have (access to) attributes and methods of class B without the need to redefine them. 1. 38
Superclass/Subclass u If class A inherits from class B, then B is called superclass of A. A is called subclass of B. Objects of a subclass can be used where objects of the corresponding superclass are expected. This is due to the fact that objects of the subclass share the same behavior as objects of the superclass. 39
Example: Person superclass subclasses Administrator 40 Faculty Student
Trees vs Forests u There are two common views of class hierarchies: u All classes are part of a single large class hierarchy. Thus, there is one class that is the original ancestor of all other classes. Smalltalk, Java and Delphi Pascal do this. u Classes are only placed in hierarchies if they have a relationship - results in a forest of many small hierarchies, but no single ancestor. C++, Objective-C, and Apple Object Pascal do this. 41
Subclassing & Modifiability u Subclassing means not only inheritance of specification but also inheritance of implementation and so can be viewed as reusability mechanism. u The degree of modifiability determines how attributes and methods inherited from a superclass can be modified in a subclass. In this context we use an approach of distinguishing modifiability of the objects state (attributes) and the objects behavior (operations). 42
For attributes 1. 2. 3. 43 No redefinition: modification is not allowed, Arbitrary redefinition: redefinition without constrained is allowed, Constrained redefinition: the domain of attributes is constrained, and Hidden redefinition: definitions of attributes are hidden in subclass to avoid conflicts.
For operations 1. Arbitrary redefinition: u 2. Constrained redefinition: u u 44 all changes to operations are allowed. the parts of the signatures of the methods in the subclass have to be subtypes of the parts of the methods of the superclass. The above are important in context with overriding and overloading of methods.
Syntax for Inheritance u Languages use a variety of different syntax to indicate inheritance: u class Wall : public Graphical. Object -- C++ u class Wall extends Graphical. Object -- Java u class Wall : Graphical. Object -- C# 45
Declaring Derived Classes in C++ u Class class_name: access_specifieropt or base_class { Member_list } u access_specifier : : = public|protected|private(default) 46
Private, Public and Protected u There are now three levels of visibility modifiers: u private: accessible only within the class definition (but memory is still found in the child class, just not accessible). u public: accessible anywhere u protected: accessible within the class definition or within the definition of child classes. u Note: Java interprets protected to mean accessible within same package 47
Syntax for Overriding u Some languages, such as C++, require that the programmer indicate in the parent class that overriding is a potential: u class Graphical. Object { u public: virtual void draw(); // can be overridden u }; u Other languages (C#, Delphi) require indications in both parent and child. And some languages (Smalltalk) do not require any indication in either parent class or child class. 48
Interfaces and Abstract Classes u u u u 49 An interface is similar to a class, but does not provide any implementation. A child class must override all methods. A middle ground is an abstract class. Here some methods are defined, and some (abstract methods) are undefined. A child class must fill in the definition for abstract methods: abstract class Window {. . . abstract public void paint (); // child class must redefine. . . } An interface is like an abstract class in which all methods are abstract. In C++ an abstract method is called a pure virtual method.
Forms of Inheritance u u u u 50 Specialization. The child class is a special case of the parent class; in other words, the child class is a subtype of the parent class. Specification. The parent class defines behavior that is implemented in the child class but not in the parent class. Construction. The child class makes use of the behavior provided by the parent class, but is not a subtype of the parent class. Generalization. The child class modifies or overrides some of the methods of the parent class. Extension. The child class adds new functionality to the parent class, but does not change any inherited behavior. Limitation. The child class restricts the use of some of the behavior inherited from the parent class. Variance. The child class and parent class are variants of each other, and the class-subclass relationship is arbitrary. Combination. The child class inherits features from more than one parent class. This is multiple inheritance and will be the subject of a later chapter.
The forms of Inheritance u Whole/Partial Inheritance: u If a class inherits all the properties and operations from its superclasses, that is Whole Inheritance; u else Partial Inheritance. Only some properties are inherited while others are suppressed. u Single(Simple)/ Multiple inheritance: u A class can inherit from only one superclass. This means the inheritance hierarchy forms a tree. u A class can have more than one superclasses. 51
Benefits of Inheritance u Software Reuse u Code Sharing u Improved Reliability u Consistency of Interface u Rapid Prototyping u Polymorphism u Information Hiding 52
Cost of Inheritance u Execution speed u Program size u Message Passing Overhead u Program Complexity 53
A Formula for Subclasses u Subclass : : =<n, C, d, m, x>, where u n is the identification or name of the subclass; u C is a set of ids of its superclasses. u d is the new space description (template) for memory of the subclass; u m is the new set of the operations’ implementation of the subclass; u x is the new interface of the subclass. 54
Inheritance and Classification u Who is the base? u Classification imply inheritance(Whole and simple inheritance) u But inheritances may affect the clear classification(for multiple inheritance, and for partial inheritance) 55
Java Messages, Instance, and Inheritance 56
Arguments and Parameters u u An argument is a value we pass to a method. A parameter is a placeholder in the called method to hold the value of the passed argument. class Application { class Account { public static void main(String[] arg) { } 57 . . . Account acct = new Account(); . . . public void add(double amt) { acct. add(400); . . . } . . . } parameter argument balance = balance + amt; . . . }
Matching Arguments and Parameters u u u 58 The number or arguments and the parameters must be the same Arguments and parameters are paired left to right The matched pair must be assignmentcompatible (e. g. you cannot pass a double argument to a int parameter)
Passing Objects to a Method u As we can pass int and double values, we can also pass an object to a method. u When we pass an object, we are actually passing the reference (name) of an object u it means a duplicate of an object is NOT created in the called method 59
Passing a Student Object In Java, when you transfer an object in a message, you actually transfer the reference of the object, i. e. , Call-BYReference. For built-in type, such as, int, double, … It is Call-By. Value. 60
Sharing an Object u We pass the same Student object to card 1 and card 2 • 61 Since we are actually passing a reference to the same object, it results in the owner of two Library. Card objects pointing to the same Student object
The Protected Modifier u The modifier protected makes a data member or method visible and accessible to the instances of the class and the descendant classes. u Public data members and methods are accessible to everyone. u Private data members and methods are accessible only to instances of the class. Example: inherit. java 62
Summary u Messages u Instance u Initialization u Inheritance u Substitution 63
- Slides: 63