Lecture 16: Object Programming Languages

Similar documents
Mid-Term 2 Grades

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

9 Objects and Classes

Lecture 12: Conditional Expressions and Local Binding

Konzepte von Programmiersprachen

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Functional Programming. Pure Functional Programming

Lecture08: Scope and Lexical Address

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

Inheritance and Polymorphism

CS 342 Lecture 8 Data Abstraction By: Hridesh Rajan

Object Oriented Paradigm

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Comp 311: Sample Midterm Examination

Making New instances of Classes

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

Turtles All The Way Down

Lecture 3: Expressions

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

Java Object Oriented Design. CSC207 Fall 2014

Data Abstraction. Hwansoo Han

Procedures. EOPL3: Section 3.3 PROC and App B: SLLGEN

Chapter 13. Object Oriented Programming

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

Principles of Programming Languages

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Object Oriented Programming. Java-Lecture 11 Polymorphism

Chapter 5 Object-Oriented Programming

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

A Brief Introduction to Scheme (II)

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Simula 67. Simula and Smalltalk. Comparison to Algol 60. Brief history. Example: Circles and lines. Objects in Simula

Simula and Smalltalk. Comparison to Algol 60. Brief history. Example: Circles and lines. Objects in Simula. John Mitchell

Comp 311 Principles of Programming Languages Lecture 21 Semantics of OO Languages. Corky Cartwright Mathias Ricken October 20, 2010

Lexical vs. Dynamic Scope

Subtyping (Dynamic Polymorphism)

Parsing Scheme (+ (* 2 3) 1) * 1

CS-202 Introduction to Object Oriented Programming

Chapter 6 Introduction to Defining Classes

Java: introduction to object-oriented features

Introduction to Scheme

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.

Outline. More optimizations for our interpreter. Types for objects

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

What about Object-Oriented Languages?

Objects, Subclassing, Subtyping, and Inheritance

Pierce Ch. 3, 8, 11, 15. Type Systems

Comp 411 Principles of Programming Languages Lecture 7 Meta-interpreters. Corky Cartwright January 26, 2018

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

More about inheritance

Inheritance and Interfaces

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

ITI Introduction to Computing II

Thanks! Review. Course Goals. General Themes in this Course. There are many programming languages. Teaching Assistants. John Mitchell.

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

G Programming Languages - Fall 2012

Scheme Quick Reference

Method Resolution Approaches. Dynamic Dispatch

Object Oriented Programming (OOP)

Recursive Functions of Symbolic Expressions and Their Computation by Machine Part I

Programming Languages

Principles of Programming Languages

CSE 401/M501 Compilers

4.2 Variations on a Scheme -- Lazy Evaluation

ITI Introduction to Computing II

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

A Small Interpreted Language

CS558 Programming Languages Winter 2013 Lecture 8

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures

MIDTERM EXAMINATION - CS130 - Spring 2005

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

COP4020 Programming Assignment 1 - Spring 2011

CMPT Data and Program Organization

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Data Abstraction. An Abstraction for Inductive Data Types. Philip W. L. Fong.

Computer Science II (20073) Week 1: Review and Inheritance

Building a system for symbolic differentiation

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.

Inheritance -- Introduction

15CS45 : OBJECT ORIENTED CONCEPTS

C311 Lab #3 Representation Independence: Representation Independent Interpreters

Chapter 5. Inheritance

Cunning Plan. One-Slide Summary. Functional Programming. Functional Programming. Introduction to COOL #1. Classroom Object-Oriented Language

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

Object Oriented Programming: Based on slides from Skrien Chapter 2

Inheritance - Assignment5

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CH. 2 OBJECT-ORIENTED PROGRAMMING

CS-XXX: Graduate Programming Languages. Lecture 22 Class-Based Object-Oriented Programming. Dan Grossman 2012

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

CS61A Midterm 2 Review (v1.1)

Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?

C++ Important Questions with Answers

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Class, Variable, Constructor, Object, Method Questions

Transcription:

Lecture 16: Object Programming Languages Introduction Corresponds to EOPL 5.1 and 5.2 Goal: to introduce Object Oriented Programming Language (OOPL) concepts using the EOPL extensible language framework Outline Introduction of basic OOPL concepts Define an OOPL extension to the PL of Chapter 3 Give 4 implementations (each more sophisticated) School of Computing Science @ Simon Fraser University Copyright Bill Havens 1

OOPL History History Programming increases complexity along with the problem domain Traditional procedural/functional PLs provide little assistance with modelling the problem Basic Idea: Programs should be models of the problem to be solved Entities in the model should be isomorphic to corresponding entities in the problem Insight came from Kristen Nygaard in Norway (1957!!!) Building complex simulations of a nuclear power plant First OOPL called SIMULA-67 (Dahl & Nygaard) See http://en.wikipedia.org/wiki/simula Extension of Algol-60 Introduced objects, classes, inheritance, virtual methods, garbage collection Progenitor of future OOPLs: Smalltalk, Flavors, CLOS, C++, Java Copyright Bill Havens 2

Basic OOPL concepts Concepts Classes Objects Message Passing Methods Persistent state Encapsulation Inheritance Overriding Polymorphism Copyright Bill Havens 3

Classes et cetera Classes Isomorphism to ontology of problem domain What are the salient entities of the problem? What are their state variables? What is the behavior of the class in the problem model? What methods can be defined to implement the desired behavior? Objects Used to populate the problem model Notion of an instance of the class What parameters differentiate members of the class? How to they interact in the problem? Copyright Bill Havens 4

Message Passing How can object interaction be modelled as message passing among objects? Art of OOPL! Messages exchanged from a sender object to a receiver object Concept of polite message passing (ACTOR formalism of Hewitt 1973) See http://en.wikipedia.org/wiki/actor_model Methods Mapping of message passing notion to remote procedure invocation (RPI) Message type = proc name; message content = proc app arguments Requires a send operator to implement RPI Blocking send with possible return value Persistent State OO programming assumes a vonneumann model of computation Program state stored in persistent state variables (object variables) Messages either interrogate or mutate the state of receiver object variables Copyright Bill Havens 5

Encapsulation Objects are opaque! Internal state and its representation are hidden from other objects Only available via message passing Notion of a public interface for accessing an object Encapsulation perhaps the most powerful concept in modern OOPLs. Makes developing/extending/maintaining large software systems possible Internal state and methods of an object can be changed without affecting the public interface (behavior) of the object Class Inheritance Notion of subclass and superclass Behavior of a class inherited by all of its subclasses recursively Both persistent state and methods Single and multiple superclass inheritance possible 1. Multiple inheritance: C++ 2. Single inheritance: Java Key to maintaining consistent object behaviour Copyright Bill Havens 6

Method Overriding Subclasses can specialize the public behaviour of their ancestor classes Adding semantics to classes means subclassing with method overriding Polymorphism A subclass object can be used wherever any of its ancestors can be used Subclass covers the public interface of its ancestors Overriding makes polymorphism possible Polymorphism is a powerful OOPL tool Copyright Bill Havens 7

Static vs. Dynamic Method Dispatch Overview Static method dispatch knows the message receiver method at compile time Dynamic method dispatch looks up receiver method at runtime Polymorphism requires dynamic method dispatching Called virtual methods in C++ Standard in Java What is this? Copyright Bill Havens 8

Polymorphic Example class Shape extends Object { abstract void draw(); // canʼt draw an arbitrary shape... } class Rectangle extends Shape { void draw () { --- draw this rectangle --- } } class Circle extends Shape { void draw () { --- draw this circle --- } } static void main() { Shape x = new Rectangle(); Shape y = new Circle; x.draw(); y.draw } What gets drawn??? 1. for static method dispatching 2. for dynamic method dispatching Copyright Bill Havens 9

OOPL specifications Specs EOPL 5.3 Single inheritance Dynamic method dispatching True polymorphism Special self variable supported Super class methods supported (static dispatching) Syntax A program is a sequence of class declarations followed by a single expression <program> --> {<class-decl>}* <expression> A class declaration is a name, superclass name, field declarations, and method declarations <class-decl> --> class <id> extends <id> {field <id>}* {<method-decl>}* Copyright Bill Havens 10

Syntax continued A method declaration looks like a procedure <method-decl> --> method <id> ({<id>}* <expression> We also add 3 new types of expressions to our interpreter language The new operator makes a new instance from a class <expression> --> new <id> ({<expression>}*) The send operator performs RPI (message passing) <expression> --> send <expression> <id> ({<expression>}*) The super operator sends a message to the static superclass of this object <expression> --> super <id> ({<expression>}*) We need to extend the PL of Chapter3 to include this new OOPL functionality Expressed / Denoted Values Extended our language significantly for Expressed Values ExpressedValue = Numer + ProcVal + Object + List(ExpressedValue) DenotedValue = Ref(ExpressedValue) Note that all variables are reference vars Classes are not expressable (like Java and C++) Copyright Bill Havens 11

Our OOPL Example class c1 extends object field i field j method initialize(x) begin set i = x set j = -(0, x) end method countup(d) begin set i = +(i, d) set j = -(j, d) end method getstate() list(i, j) let t1 = 0 t2 = 0 o1 = new c1(3) in begin set t1 = send o1 getstate(); send o1 countup(2); set t2 = send o1 getstate(); list(t1, t2) end What does this program compute? What functionality do we need to implement? School of Computing Science @ Simon Fraser University Copyright Bill Havens 12

1st OOPL Implementation Overview Define an implementation interface that each version of the OOPL must implement Interface 1. elaborate-class-decls : compiles a runtime representation of the class declarations useable by the augmented interpreter 2. find-method-and-apply : performs message passing; looks up named method in the class hierarchy and applies it to the supplied arguments 3. object->class-name : given an object, returns the name of its class 4. new-object : the constructor which makes a new object from a class name and specified initialization arguments. Now we can extend the interpreter for eval-program and eval-expression Next we will give a first implementation of the 4 interface methods above Copyright Bill Havens 13

Extended Interpreter Eval Program (define eval-program (lambda (pgm) (cases program pgm (a-program (c-decls exp) (elaborate-class-decls! c-decls) (eval-expression exp (empty-env)))))) Only change is to compile class declarations Simplest possible implementation Just use the abstract datatype representation of the classes themselves! (define the-class-env '()) (define elaborate-class-decls! (lambda (c-decls) (set! the-class-env c-decls))) Copyright Bill Havens 14

Eval Expression Extended Interpreter (contd) (define eval-expression (lambda (exp env) (cases expression exp... % as before (new-object-exp (class-name rands) (let ((args (eval-rands rands env)) (obj (new-object class-name))) (find-method-and-apply 'initialize class-name obj args) obj)) (method-app-exp (obj-exp method-name rands) (let ((args (eval-rands rands env)) (obj (eval-expression obj-exp env))) (find-method-and-apply method-name (object->class-name obj) obj args))) (super-call-exp (method-name rands) (let ((args (eval-rands rands env)) (obj (apply-env env 'self))) (find-method-and-apply method-name (apply-env env '%super) obj args))) ))) Lets consider each new clause in turn... School of Computing Science @ Simon Fraser University Copyright Bill Havens 15

To send a message: Message Send (v1) 1. evaluate the receiver object expression 2. evaluate the message operands 3. lookup the correct method in the class hierarchy 4. Call the method with the evaluated arguments 5. Return the result as the value of the message send Code (repeated) (method-app-exp (obj-exp method-name rands) (let ((args (eval-rands rands env)) (obj (eval-expression obj-exp env))) (find-method-and-apply method-name (object->class-name obj) obj args))) Only need to implement function find-method-and-apply School of Computing Science @ Simon Fraser University Copyright Bill Havens 16

function find-method-and-apply (define find-method-and-apply (lambda (m-name host-name self args) (if (eqv? host-name 'object) (eopl:error 'find-method-and-apply "No method for name ~s" m-name) (let ((m-decl (lookup-method-decl m-name (class-name->method-decls host-name)))) (if (method-decl? m-decl) (apply-method m-decl host-name self args) (find-method-and-apply m-name (class-name->super-name host-name) self args)))))) function lookup-method-decl looks up the correct method implementation in the class declaration hierarchy for the host (declared) class of the object recursively. Note failure on class object Method evaluation analogous to closure evaluation Need to define method called apply-method... School of Computing Science @ Simon Fraser University Copyright Bill Havens 17

function apply-method Evaluate the body of the method in the environment of the objects declared and inherited variables (fields) These variables are containted in the list (chain) representing the object. Includes 2 special variables 1. Variable self which references the receiver object 2. Variable %super which references the superclass of the receiver Need a way of kowing whether to start at the class (host) of receiver or its superclass or higher. function view-object-as is used to search this chain (define view-object-as (lambda (parts class-name) (if (eqv? (part->class-name (car parts)) class-name) parts (view-object-as (cdr parts) class-name)))) Copyright Bill Havens 18

Building the new environment Given the right view of the inheritance hierarchy we can build a NEW environment for the message send (define build-field-env (lambda (parts) (if (null? parts) (empty-env) (extend-env-refs (part->field-ids (car parts)) (part->fields (car parts)) (build-field-env (cdr parts)))))) Now apply-method does the usual evaluation of the method body in the new environment (define apply-method (lambda (m-decl host-name self args) (let ((ids (method-decl->ids m-decl)) (body (method-decl->body m-decl)) (super-name (class-name->super-name host-name))) (eval-expression body (extend-env (cons '%super (cons 'self ids)) (cons super-name (cons self args)) (build-field-env (view-object-as self host-name))))))) School of Computing Science @ Simon Fraser University Copyright Bill Havens 19

To create a new object New Operator (v1) 1. evaluate the class-name expression 2. evaluate the initialization operands 3. find the correct initialize method for the class 4. apply the method to the operands 5. return the new object Code (repeated) (new-object-exp (class-name rands) (let ((args (eval-rands rands env)) (obj (new-object class-name))) (find-method-and-apply 'initialize class-name obj args) obj)) Need only function new-object School of Computing Science @ Simon Fraser University Copyright Bill Havens 20

function new-object (define new-object (lambda (class-name) (if (eqv? class-name 'object) '() (let ((c-decl (lookup-class class-name))) (cons (make-first-part c-decl) (new-object (class-decl->super-name c-decl))))))) (define make-first-part (lambda (c-decl) (a-part (class-decl->class-name c-decl) (make-vector (length (class-decl->field-ids c-decl)))))) This implementation represents objects (instances) as a linked-list of parts Each part is a pair: (<class-name> <vector of fields>) Note: simple accessor functions are assumed here Copyright Bill Havens 21

Super message call (v1) To send a message to the super class of an object: 1. Evaluate the operands of the message 2. Get reference to this object (self) 3. Lookup %super variable in the current environment 4. find-and-apply the method in the field view (using view-object-as) of the super class Code DONE! (super-call-exp (method-name rands) (let ((args (eval-rands rands env)) (obj (apply-env env 'self))) (find-method-and-apply method-name (apply-env env '%super) obj args))) School of Computing Science @ Simon Fraser University Copyright Bill Havens 22