Polymorphism, Dynamic Typing, and Dynamic Binding Copyright © 2012 by Yong-Gu Lee

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms
Advertisements

1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
The Preprocessor Underlying C Language Features Copyright © 2012 by Yong-Gu Lee
Written by: Dr. JJ Shepherd
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Compiler Construction
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Polymorphism, Virtual Methods and Abstract Classes.
Static and Dynamic Behavior Fall 2005 OOPD John Anthony.
OOP Spring 2007 – Recitation 81 Object Oriented Programming Spring 2007 Recitation 8.
Run-time Environment and Program Organization
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
C++ fundamentals.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
Java and C++, The Difference An introduction Unit - 00.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
More on Classes Inheritance Copyright © 2012 by Yong-Gu Lee
Static and Dynamic Behavior CMPS Power of OOP Derives from the ability of objects to change their behavior dynamically at run time. Static – refers.
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Object Oriented Programming Elhanan Borenstein Lecture #4.
Program Looping Making Decisions Copyright © 2012 by Yong-Gu Lee
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSSE501 Object-Oriented Development. Chapter 12: Implications of Substitution  In this chapter we will investigate some of the implications of the principle.
Objective-C OOP Spring OOP Conceptually the same as C++, Java, and all other object oriented languages The syntax, however… …is, well, different.
Objective-C1 CS151 Presentation: Objective C Kai Tai Pang William Sze.
CSSE501 Object-Oriented Development. Chapter 11: Static and Dynamic Behavior  In this chapter we will examine the differences between static and dynamic.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Implementing Subprograms What actions must take place when subprograms are called and when they terminate? –calling a subprogram has several associated.
Types in programming languages1 What are types, and why do we need them?
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
CS536 Semantic Analysis Introduction with Emphasis on Name Analysis 1.
Object-Oriented Programming Chapter Chapter
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Polymorphism, Virtual Methods and Interfaces Version 1.1.
CS212: Object Oriented Analysis and Design Lecture 19: Exception Handling.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Written by: Dr. JJ Shepherd
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Prof. Necula CS 164 Lecture 171 Operational Semantics of Cool ICOM 4029 Lecture 10.
Polymorphism Lecture - 9.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Generics, Exception and Undo Command. A Generic Stack Class AStack uses generic. In the main method, we have 2 instances of AStack, each type is Integer.
Design issues for Object-Oriented Languages
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Motivation and Overview
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Course Overview PART I: overview material PART II: inside a compiler
Programming in C Pointers and Arrays.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Polymorphism, Dynamic Typing, and Dynamic Binding Copyright © 2012 by Yong-Gu Lee

polymorphism, dynamic typing, and dynamic binding. Polymorphism enables programs to be developed so that objects from different classes can define methods that share the same name. Dynamic typing defers the determination of the class that an object belongs to until the program is executing. Dynamic binding defers the determination of the actual method to invoke on an object until program execution time.

Polymorphism ClassA: int class_a_property; class_a_property; -(void) action { ClassB: NSObject ClassB -(void) action { action"); :13: Chapt9[3695:707] ClassA action :13: Chapt9[3695:707] ClassB action int main (int argc, const char * argv[]) { ClassA* class_a=[[ClassA alloc]init]; ClassB* class_b=[[ClassB alloc]init]; [class_a action]; [class_b action]; } return 0; }

Dynamic typing& binding and the id type ClassA: int class_a_property; class_a_property; -(void) action { ClassB: NSObject ClassB -(void) action { action"); int main (int argc, const char * argv[]) { ClassA* class_a=[[ClassA alloc]init]; ClassB* class_b=[[ClassB alloc]init]; id instance_id; instance_id = class_b; [instance_id action]; instance_id = class_a; [instance_id action]; } return 0; } :17: Chapt9[3738:707] ClassB action :17: Chapt9[3738:707] ClassA action

Compile time versus runtime checking ClassA: int class_a_property; -(void) action; class_a_property; -(void) action { action"); } -(void) action_only_in_ClassA ClassB: NSObject -(void) action; ClassB -(void) action { action"); } -(void) action_only_in_ClassB { int main (int argc, const char * argv[]) { ClassA* class_a=[[ClassA alloc]init]; ClassB* class_b=[[ClassB alloc]init]; //Compile time error [class_a action_only_in_ClassB]; //Run time error id instance_id; instance_id = class_a; [instance_id action_only_in_ClassB]; } return 0; } :54: Chapt9[4423:707] -[ClassA action_only_in_ClassB]: unrecognized selector sent to instance 0x :54: Chapt9[4423:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ClassA action_only_in_ClassB]: unrecognized selector sent to instance 0x ' *** First throw call stack: ( 0 CoreFoundation 0x00007fff84709fc6 __exceptionPreprocess libobjc.A.dylib 0x00007fff85845d5e objc_exception_throw CoreFoundation 0x00007fff847962ae -[NSObject doesNotRecognizeSelector:] CoreFoundation 0x00007fff846f6e73 ___forwarding___ CoreFoundation 0x00007fff846f6c88 _CF_forwarding_prep_ Chapt9 0x cc9 main Chapt9 0x b24 start + 52 ) terminate called throwing an exceptionsharedlibrary apply-load-rules all Current language: auto; currently objective-c

The id Data Type and Static Typing If an id data type can be used to store any object, why don’t you just declare all your objects as type id? For several reasons, you don’t want to get into the habit of overusing this generic class data type. First, when you define a variable to be an object from a particular class, you are using what’s known as static typing. When you use static typing, the compiler ensures, to the best of its ability, that the variable is used consistently throughout the program. The compiler can check to ensure that a method applied to an object is defined or inherited by that class; if not, it issues a warning message.

Argument and Return Types with Dynamic Binding If you use dynamic binding to invoke a method, note the following rule: If a method with the same name is implemented in more than one of your classes, each method must agree on the type of each argument and the type of value it returns so that the compiler can generate the correct code for your message expressions. The compiler performs a consistency check among each class declaration it has seen If one or more methods conflict in either argument or return type, the compiler issues a warning message. If the inconsistency between two methods is just a different type of object (for example, the Fraction’s add: method takes a Fraction object as its argument and returns one, and the Complex’s add: method takes and returns a Complex object), the compiler will still generate the correct code because memory addresses (that is, pointers) are passed as references to objects anyway.

Selectors The method name part of a message is sometimes referred to as the selector or method selector because it is used by the runtime to select which of the receiver’s methods to execute. Selectors are just names, they don’t carry any type information. Objective-C defines a type, SEL, for holding a representation of a selector. A SEL has a one-to-one relationship with the selector name but a SEL is not itself a string. All selectors with the same name have the same SEL and different names always correspond to different SELs. Internally, Objective-C uses the SEL type to identify methods for reasons of efficiency. Using strings would be slow; just testing to see if two strings are the same requires looping over all the characters in the string.

The compiler converts a method name into a SEL: SEL aSelector someMessageName ); If the method has any arguments, you must remember to include the colons when you create a SEL. They are part of the method aMethod ) aMethod: ) are different SELs.

SELs can be used to make the message part of a message expression dynamic. NSObject defines the following method: - (id)performSelector:(SEL)aSelector When performSelector: is executed, the object executes the selector that is its argument. The following two lines of code are equivalent: [aShape draw]; [aShape draw )];

Asking Questions About Classes

Exeption handling with ClassA: int class_a_property; -(void) action; class_a_property; -(void) action { action"); } -(void) action_only_in_ClassA ClassB: NSObject -(void) action; ClassB -(void) action { action"); } -(void) action_only_in_ClassB { int main (int argc, const char * argv[]) { ClassA* class_a=[[ClassA alloc]init]; id instance_id; instance_id = { //Run time error [instance_id action_only_in_ClassB]; (NSException *exception) { [exception name], [exception reason]); } return 0; } [Switching to process 4260 thread 0x0] [4260:707] -[ClassA action_only_in_ClassB]: unrecognized selector sent to instance 0x [4260:707] Caught NSInvalidArgumentException-[ClassA action_only_in_ClassB]: unrecognized selector sent to instance 0x