INHERITANCE, SUBTYPING, PROTOTYPES in Object-Oriented Languages. Orlin Grigorov McMaster University CAS 706, Fall 2006 ogrigorov@gmail.



Similar documents
Multiple Dispatching. Alex Tritthart WS 12/13

Announcements FORTRAN ALGOL COBOL. Simula & Smalltalk. Programming Languages

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

History OOP languages Year Language 1967 Simula Smalltalk

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Programming Languages

Structural Design Patterns Used in Data Structures Implementation

Data Abstraction and Hierarchy

Object Oriented Databases. OOAD Fall 2012 Arjun Gopalakrishna Bhavya Udayashankar

Java Application Developer Certificate Program Competencies

THE IMPACT OF INHERITANCE ON SECURITY IN OBJECT-ORIENTED DATABASE SYSTEMS

MCI-Java: A Modified Java Virtual Machine Approach to Multiple Code Inheritance

Inheritance, overloading and overriding

Static Typing for Object-Oriented Programming

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Glossary of Object Oriented Terms

Description of Class Mutation Mutation Operators for Java

CSCI 3136 Principles of Programming Languages

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Parsing Technology and its role in Legacy Modernization. A Metaware White Paper

CS-XXX: Graduate Programming Languages. Lecture 25 Multiple Inheritance and Interfaces. Dan Grossman 2012

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

MOOL: an Object-Oriented Programming Language with Generics and Modules. María Lucía Barrón Estrada

Object Instance Profiling

Case studies: Outline. Requirement Engineering. Case Study: Automated Banking System. UML and Case Studies ITNP090 - Object Oriented Software Design

Obfuscation: know your enemy

2! Multimedia Programming with! Python and SDL

Chapter 8 The Enhanced Entity- Relationship (EER) Model

Neural Pascal. A Language for Neural Network Programming. 1. Introduction

Concepts and terminology in the Simula Programming Language

Inheritance in Programming Languages

Languages september 12, 2015 Éric Lévénez < FORTRAN III end-1958 FORTRAN II FORTRAN I october 1956

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Object-based vs. Class-based Languages

CS 111 Classes I 1. Software Organization View to this point:

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

Implementing Statically Typed Object-Oriented Programming Languages

Write Barrier Removal by Static Analysis

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Habanero Extreme Scale Software Research Project

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

The Smalltalk Programming Language. Beatrice Åkerblom

Java Software Structures

Advanced Data Structures

Chapter 5 Names, Bindings, Type Checking, and Scopes

Adding diagrams to Scaladoc

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

CSE 307: Principles of Programming Languages

Visualizing Software Projects in JavaScript

In order to understand Perl objects, you first need to understand references in Perl. See perlref for details.

Object Oriented Design

Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance

Options. Acquiring an application. Custom development. Off-the-shelf. Trade-off. Outsourcing development

Tutorial on Writing Modular Programs in Scala

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Application Centric Infrastructure Object-Oriented Data Model: Gain Advanced Network Control and Programmability

Lecture 1: Introduction

PHP Code Design. The data structure of a relational database can be represented with a Data Model diagram, also called an Entity-Relation diagram.

Going Interactive: Combining Ad-Hoc and Regression Testing

DESIGN PATTERN GENERATOR FOR PYTHON

CS193j, Stanford Handout #10 OOP 3

Semantic Analysis: Types and Type Checking

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014

Enumerated Types in Java

Patterns in. Lecture 2 GoF Design Patterns Creational. Sharif University of Technology. Department of Computer Engineering

The Phases of an Object-Oriented Application

Chapter 13 Computer Programs and Programming Languages. Discovering Computers Your Interactive Guide to the Digital World

Universität Karlsruhe (TH) Forschungsuniversität gegründet Inheritance Depth as a Cost Factor in Maintenance

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

Lab Manual: Using Rational Rose

Abstract. a

PHP Object Oriented Classes and objects

International Journal of Software and Web Sciences (IJSWS)

On the (un)suitability of Java to be the first programming language

Objectives. Chapter 2: Operating-System Structures. Operating System Services (Cont.) Operating System Services. Operating System Services (Cont.

Programming Languages Featherweight Java David Walker

Semester Review. CSC 301, Fall 2015

Lecture 9. Semantic Analysis Scoping and Symbol Table

Building Java Programs

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

LINKED DATA STRUCTURES

Functional Programming

Xcode Project Management Guide. (Legacy)

Johannes Sametinger. C. Doppler Laboratory for Software Engineering Johannes Kepler University of Linz A-4040 Linz, Austria

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

Programming Languages

Tampereen teknillinen yliopisto. Ohjelmistotekniikan laitos. Raportti 6 Tampere University of Technology. Department of Software Systems.

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Data Structures in the Java API

Lecture 15: Inheritance

Transcription:

INHERITANCE, SUBTYPING, PROTOTYPES in Object-Oriented Languages Orlin Grigorov McMaster University CAS 706, Fall 2006 ogrigorov@gmail.com

Two kinds of OO programming languages CLASS-BASED Classes Instances Inheritance PROTOTYPE-BASED No distinction between classes and instances Objects (similar to instances) Prototypes (cloning existing objects) e.g. Java, C++, C# e.g. JavaScript, Lua

Outline Inheritance Single Multiple Interfaces Mixins Subtyping Prototypes

Inheritance

Inheritance (definition) Refers to the fact that the definition of a new class can assume (or rely upon the existence of) another definition. Alternatively, it makes a previously defined structure available for incorporation in a new one. A method of code sharing; If one class inherits from another, the inheriting class specializes a class which is more general. Logical relationship between classes (specialization/generalization); Enables subtypes to be produced given a definition of a supertype. Type-based account;

Inheritance (terminology) Subclass or child class or derived class: inherits all properties of its parent class, as well as adds other properties of its own. Think of it as: An extension of the parent class (larger set of properties); A contraction of the parent class (more specialized) Superclass or parent class or base class: a class that is one level higher in the class hierarchy than its child classes.

Inheritance is is a kind of relation * The relation applies to classes, not instances! Food Fruit Meat Apple Orange Chicken Pork

Reasons to use inheritance Code reuse Because a child class can inherit behaviour from a parent class, the code does not need to be rewritten for the child. Concept reuse If a child overrides behaviour defined in the parent, although no code is shared, they share the definition of the method

Inheritance in various languages C++ class B : public A {.. } C# class B : A {.. } CLOS (defclass B (A) () ) JAVA class B extends A {.. } Object Pascal type Python class B(A): def init (self):... Ruby B = object (A)... end; class B < A... end

Inheritance in various languages (cont.): Java, Smalltalk, Objective-C, Delphi Pascal: TREES Require every class to inherit from an existing parent class; A single root that is ancestor to all objects (termed Object in Smalltalk and Objective-C, TObject in Delphi Pascal); Any behaviour provided by the root inherited in all objects; Thus, every object is guaranteed to possess a common minimal level of functionality. -continues-

Inheritance in various languages (cont.): DISADVANTAGE: combines all classes into a tightly coupled unit. C++ and Apple Pascal: FOREST Do not require every class to inherit from a parent; Not forced to carry a large library of classes, only a few of which may be used in any one program;..but no programmer-defined functionality that all objects are guaranteed to possess.

Tree vs. Forest Tree Advantages: Single class hierarchy; Standardization: the functionality of the root is inherited by all objects all have some basic functionality. Disadvantages: Tight coupling; Larger libraries. Forest Advantages: Many smaller hierarchies; Smaller libraries of classes for application, less coupling possible. Disadvantages: No shared functionality among all objects.

Single Inheritance A class can have only a single superclass; The data and behavior of a particular superclass is available to the subclass; Advantages: Simple to include in the design Code re-use is very simple to obtain

Single Inheritance (cont.) There is only 1 root class There is only a linear sequence of classes between Apple and Food Apple Fruit Food

Single Inheritance (cont.) Property: it is always transitive Food Fruit Fruit Apple

Single Inheritance (cont.) Disadvantages: Some models cannot be accurately modeled using Single Inheritance; Leads to duplicate code; Electronic Device DVD Player VCR Player DVD buttons VCR buttons

Multiple Inheritance A class can inherit from anywhere in a class hierarchy; A child class can have more than one parent; Provides more realistic framework; e.g. A child has two biological parents. Available in some OO languages, such as C++ and Eiffel

Multiple Inheritance (cont.) Structure is a lattice or Directed Acyclic Graph Problems: Replication of inherited slots; Meaning of the program of the program can be different depending on search algorithm. A B C D

example (demonstrates concept, will not compile) class A { abstract void printme(); } A class B extends A { void printme() { -- B -- } } B C class C extends A { void printme() { -- C -- } } D class D extends B, C {} A d = new D(); d.printme(); //problem, which one?!

C++, resolve manually: option 1 Explicitly qualify the call by prefixing it with the name of the intended superclass using the scope resolution operator: d.b::printme(); OR d.c::printme();

C++, resolve manually: option 2 Add a new method foo to class D: class D : public B, public C { void foo(void) { B::printMe(); //one, the other, C::printMe(); //both or neither } } Similar solution in Eiffel: use feature renaming, see next slide

Eiffel class D inherit B rename printme as printme_b select printme_b end; C rename printme as printme_c end... end This makes printme_b as the version of printme inherited from B. It also becomes the one that will be used in D.

C++: virtual Follows each inheritance path separately. so a D object would actually contain two separate A objects; If the inheritance from A to B and from A to C are both marked virtual, creates only one A object. class B : virtual A Uses of A's members work correctly.

Perl Perl handles this by specifying the inheritance classes as an ordered list. Class B and its ancestors would be checked before class C and its ancestors, so the method in A would be inherited through B.

Python Python had to deal with this upon the introduction of new-style classes, all of which have a common ancestor, object. Python creates a list of the classes that would be searched in left-first depth-first order (D, B, A, C, A) and then removes all but the last occurrence of any repeated classes. Thus, the method resolution order is: D, B, C, A.

Interfaces: Java Allows only single inheritance; Allows the multiple inheritance of interfaces. Interface Abstract class In interfaces you cannot attach any behaviour, but can implement multiple interfaces; whereas in abstract classes you can define behaviour, but inherit only one abstract class. Also in Objective-C (protocols), PHP, C#.

Interfaces: example in Java interface B { void printme(); } interface C { void printme(); } class A {... } class D extends A implements B { void printme() { -- B -- } }

Alternative solution: Linearization 1. Flatten the inheritance structure into a linear chain without duplicates; 2. Search the chain in order to find slots (like in single inheritance); B and C both define x printme(); One will be masked off by the algorithm. * The selection is arbitrary unless more information is given. B x A D x C The order, in which the algorithm encounters superclasses is important; Programmer can set the order though.

Linearization: problem Inherited classes are not guaranteed communication with their direct ancestors; The algorithm can insert unrelated classes between an inheriting class and one of its direct ancestors: A A B C D B D C Consequence: A cannot communicate directly with C, and B cannot communicate directly with D

Linearization: implementation Visit each node and put it into a list; Once the whole graph is traversed and all nodes collected remove all duplicates. 2 ways to remove them: Starting from the front...or the back.

Mixins Referred to as abstract subclasses ; They represent specification that may be applied to various parent classes to extend them with the same set of features. Available in Lisp, Scala, Ruby, Smallscript and CLOS. Has been ported to Java as well. Alternative approach to multiple inheritance.

Mixins: example in Scala class Point2D(xc: Int, yc: Int) { val x = xc; val y = yc; //plus methods for manipulating 2D points } class ColouredPoint2D(u: Int, v: Int, c: String) extends Point2D(u, v) { var colour = c; def setcolour(newcol: String): Unit = colour = newcol; } class Point3D(xc: Int, yc: Int, zc: Int) extends Point2D(xc, yc) { val z = zc; //plus methods for manipulating 3D points } class ColouredPoint3D(xc: Int, yc: Int, zc: Int, col: String) extends Point3D(xc, yc, zc) with ColouredPoint2D(xc, yc, col);

Mixins: example in Scala (cont.) Point2D ColouredPoint2D Point3D ColouredPoint3D ColouredPoint2D

Subtyping

Subtyping Subtyping consists of the rules by which objects of one type (class) are determined to be acceptable in contexts that expect another type (class). The rules determine the legality of programs Subtyping should be based on the behaviour of objects.

Subtyping RULES: 1) If instances of class B meet the external interface of class A, then B should be a subtype of A. 2) One can use an instance of class B whenever an instance of class A is needed. Guarantee: always the same behaviour!

Subtyping vs. Interface Inheritance Subtyping If B is a subtype of A, safe to use B instead of A always the same behaviour. Interface Inheritance If B has simply inherited the interface of A, then it is legal to use B instead of A, but no guarantee that it will do what you want.

Subtyping should not be equated with Inheritance Stack DEQueue Consider Stack as a subtype of DEQueue (double-ended queue) In Trellis/Owl, Simula and Sather, class Stack is a subtype of DEQueue iff Stack is a subclass of DEQueue. If Stack is re-implemented, so that it becomes selfcontained and inherits from no parent class, then the assumption that Stack is a subtype of DEQueue will no longer be legal. Implementation hierarchy need not be the same as the type hierarchy.

Subtyping should not be equated with Inheritance (cont.) Stack inherits from DEQueue, but is not a subtype of it (excludes the operation that adds elements to the back of the queue). DEQueue is a subtype of Stack, but does not inherit from Stack. Stack (abstraction) subtype of DEQueue (abstraction) implements Stack (implementation) subtype of inherits from implements DEQueue (implementation)

Subtyping in various languages Statically typed languages: subtyping rules are extremely important as they determine the legality of programs. e.g. C++, Java Dynamically typed languages: subtyping rules affect the result of type predicates. e.g. CLOS, Smalltalk

Prototypes

Prototypes Object-Oriented programming without classes! No distinction between classes and instances. There are only objects, which are similar to instances. e.g.javascript, Lua, Self, Kevo, NewtonScript, Mica, Obliq, Factor, Io, Lisaac, REBOL, Agora, Cecil and many others. prototype-based programming object-based programming

Prototypes (cont.) Create new objects by cloning, not instantiation. Analogy: Building an object in a class-based language is like building a house from a plan, while building an object in a prototype-based language is like building a house like the neighbors.

Side by side: Java and JavaScript Java public class Employee { public String name; public String dept; public Employee () { this.name = ""; this.dept = "general"; } } public class Manager extends Employee { public Employee[] reports; public Manager () { this.reports = new Employee[0]; } } public class WorkerBee extends Employee { public String[] projects; public WorkerBee() { this.projects = new String[0]; } } JavaScript function Employee () { this.name = ""; this.dept = "general"; } function Manager () { this.reports = []; } Manager.prototype = new Employee; function WorkerBee() { this.projects = []; } WorkerBee.prototype= new Employee;

Java vs. JavaScript Class-based Class and instance are distinct entities. Define a class with a class definition; instantiate a class with constructor methods. Create a single object with the new operator. Construct an object hierarchy by using class definitions to define subclasses of existing classes. Inherit properties by following the class chain. Class definition specifies all properties of all instances of a class. No way to add properties dynamically at runtime. All objects are instances. Define and create a set of objects with constructor functions. The same. Prototype-based Construct an object hierarchy by assigning an object as the prototype associated with a constructor function. Inherit properties by following the prototype chain. Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.

References Budd, Timothy. An Introduction to Object-Oriented Programming. 3rd ed. Addison-Wesley, 2002. Craig, Iain. The Interpretation of Object-Oriented Programming Languages. Springer, 1999. "Multiple Inheritance." Wikipedia. 13 Nov. 2006 <http://en.wikipedia.org/wiki/multiple_inheritance>. "Prototype-Based Programming." Wikipedia. 13 Nov. 2006 <http://en.wikipedia.org/wiki/prototype-based_programming>. Merizzi, Nicholas. "Object Oriented, Classes, Objects, Inheritance, and Typing." Jan. 2005. 13 Nov. 2006. Sykes, Ed. "Object Oriented Languages." 13 Nov. 2006.

END Time for questions and discussions

Cut slides follow..

Abstract Classes Serve as place holders in an inheritance graph; Define only properties and behaviours required by many other classes; Cannot be instantiated! e.g. AST for expressions Expression abstract : doesn t make sense to instantiate Constant Intconst Variable Unaryop Application Boolconst Floatconst.. Stringconst Binaryop.

Abstract Classes in various languages Some languages, like Java and Dylan, allow abstract classes (and methods) to be explicitly marked. Java: public abstract class A { public abstract void b(..);.. } Similar marking scheme in Dylan. In Eiffel: distinction achieved by means of the deferred annotation, which means that implementation of a feature is deferred until a later class.

Abstract Classes in various languages (cont.) In C++, a method can be defined as being virtual void. The method is a virtual void, but.. its implementation is deferred to the subclasses of the class. virtual int add1(int y) = 0 The =0 is the void part of virtual void. No class annotation for an abstract class in C++.