CSE341: Programming Languages Lecture 23 Multiple Inheritance, Mixins, Interfaces, Abstract Methods. Dan Grossman Autumn 2018

Similar documents
Today. CSE341: Programming Languages. Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins. Ruby instance variables and methods

Interfaces, Mixins, & Multiple Inheritance

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

CSE 341: Programming Languages. Section AC with Nate Yazdani

Late Binding; OOP as a Racket Pattern

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 20 Arrays and Such, Blocks and Procs, Inheritance and Overriding. Dan Grossman Spring 2017

Exceptions and Continuations. Lecture #19: More Special Effects Exceptions and OOP. Approach II: Non-Standard Return. Approach I: Do Nothing

CSE341: Programming Languages Lecture 25 Subtyping for OOP; Comparing/Combining Generics and Subtyping. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 22 OOP vs. Functional Decomposition; Adding Operators & Variants; Double-Dispatch. Dan Grossman Autumn 2018

CSE 341, Autumn 2015, Ruby Introduction Summary

CSE341, Fall 2011, Lecture 26 Summary

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

CS558 Programming Languages Winter 2013 Lecture 8

Overview. Elements of Programming Languages. Objects. Self-Reference

CS152: Programming Languages. Lecture 23 Advanced Concepts in Object-Oriented Programming. Dan Grossman Spring 2011

Project 6 Due 11:59:59pm Thu, Dec 10, 2015

Inheritance and Substitution (Budd chapter 8, 10)

Don t Believe the Hype. CS152: Programming Languages. Lecture 21 Object-Oriented Programming. Class-based OOP. So what is OOP?

Ruby. Mooly Sagiv. Most slides taken from Dan Grossman

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

Overview. Elements of Programming Languages. Objects. Self-Reference

Inheritance. Finally, the final keyword. A widely example using inheritance. OOP: Inheritance 1

CS 11 python track: lecture 4

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

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

CS 251 Intermediate Programming Inheritance

Java Fundamentals (II)

Programming Languages

CS558 Programming Languages

CPS 506 Comparative Programming Languages. Programming Language

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

CSE341 Spring 2017, Final Examination June 8, 2017

Inheritance in Ruby. You are familiar with the idea of inheritance and how to use this in programming.

Data Abstraction. Hwansoo Han

Type Hierarchy. Lecture 6: OOP, autumn 2003

CS-XXX: Graduate Programming Languages. Lecture 23 Types for OOP; Static Overloading and Multimethods. Dan Grossman 2012

Programming Languages & Paradigms PROP HT Abstraction & Modularity. Inheritance vs. delegation, method vs. message. Modularity, cont d.

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

CSE341 Spring 2017, Final Examination June 8, 2017

Project 2 Due 11:59:59pm Wed, Mar 7, 2012

Inheritance. OOP: Inheritance 1

Java Object Oriented Design. CSC207 Fall 2014

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

OBJECT ORIENTED PROGRAMMING

CSE 401/M501 Compilers

CSci 4223 Lecture 18 April 3, 2013 Topics: OOP vs. FP

Objects, Subclassing, Subtyping, and Inheritance

MIT Semantic Analysis. Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology

Object Oriented Programming: Based on slides from Skrien Chapter 2

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

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

Rules and syntax for inheritance. The boring stuff

PROGRAMMING LANGUAGE 2

Smalltalk: developed at Xerox Palo Alto Research Center by the Learning Research Group in the 1970 s (Smalltalk-72, Smalltalk-76, Smalltalk-80)

Inheritance and object compatibility

From IMP to Java. Andreas Lochbihler. parts based on work by Gerwin Klein and Tobias Nipkow ETH Zurich

Inheritance (Part 5) Odds and ends

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 10

Records. ADTs. Objects as Records. Objects as ADTs. Objects CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 15: Objects 25 Feb 05

Practice for Chapter 11

CSE341: Programming Languages Spring 2017 Unit 7 Summary Dan Grossman, University of Washington

Concepts of Programming Languages

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

Inheritance (Chapter 7)

Object typing and subtypes

C++ Yanyan SHEN. slide 1

OVERRIDING. 7/11/2015 Budditha Hettige 82

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

17 Multiple Inheritance and ADT Extensions

Subtyping (Dynamic Polymorphism)

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Lecture 18 CSE11 Fall 2013 Inheritance

CS-202 Introduction to Object Oriented Programming

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Inheritance. Transitivity

COMP 110/L Lecture 19. Kyle Dewey

CSE 341: Programming Languages

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

CSE : Python Programming

CSE 505, Fall 2007, Final Examination 10 December Please do not turn the page until everyone is ready.

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Lecture Notes on Programming Languages

Implements vs. Extends When Defining a Class

UNIVERSITY OF OSLO Department of Informatics. Traits in Java. Master thesis. Kjetil Østerås

CMSC 132: Object-Oriented Programming II

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

[ L5P1] Object-Oriented Programming: Advanced Concepts

Inheritance and Substitution גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Last name:... First name:... Department (if not D-INFK):...

Inheritance. A key OOP concept

Object-Oriented Concepts

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CSE341: Programming Languages Lecture 26 Course Victory Lap. Dan Grossman Spring 2016

History C++ Design Goals. How successful? Significant constraints. Overview of C++

Transcription:

CSE341: Programming Languages Lecture 23 Multiple Inheritance, Mixins, Interfaces, Abstract Methods Dan Grossman Autumn 2018

What next? Have used classes for OOP's essence: inheritance, overriding, dynamic dispatch Now, what if we want to have more than just 1 superclass Multiple inheritance: allow > 1 superclasses Useful but has some problems (see C++) Ruby-style mixins: 1 superclass; > 1 method providers Often a fine substitute for multiple inheritance and has fewer problems (see also Scala traits) Java/C#-style interfaces: allow > 1 types Mostly irrelevant in a dynamically typed language, but fewer problems 2

Multiple Inheritance If inheritance and overriding are so useful, why limit ourselves to one superclass? Because the semantics is often awkward (this topic) Because it makes static type-checking harder (not discussed) Because it makes efficient implementation harder (not discussed) Is it useful? Sure! Example: Make a ColorPt3D by inheriting from Pt3D and ColorPt (or maybe just from Color) Example: Make a StudentAthlete by inheriting from Student and Athlete With single inheritance, up copying code or using non-oopstyle helper methods 3

Trees, dags, and diamonds Note: The phrases subclass, superclass can be ambiguous There are immediate subclasses, superclasses And there are transitive subclasses, superclasses Single inheritance: the class hierarchy is a tree Nodes are classes Parent is immediate superclass Any number of children allowed Multiple inheritance: the class hierarchy no longer a tree Cycles still disallowed (a directed-acyclic graph) If multiple paths show that X is a (transitive) superclass of Y, then we have diamonds 4 A B C D V E X Y W Z

What could go wrong? If V and Z both define a method m, what does Y inherit? What does super mean? Directed ress useful (e.g., Z::super) V X Y W Z What if X defines a method m that Z but not V overrides? Can handle like previous case, but sometimes undesirable (e.g., ColorPt3D wants Pt3D's overrides to win ) If X defines fields, should Y have one copy of them (f) or two (V::f and Z::f)? Turns out each behavior can be desirable (next slides) So C++ has (at least) two forms of inheritance 5

3DColorPoints If Ruby had multiple inheritance, we would want ColorPt3D to inherit methods that share one @x and one @y class Pt attr_accessor :x, :y class ColorPt < Pt attr_accessor :color class Pt3D < Pt attr_accessor :z # override some methods class ColorPt3D < Pt3D, ColorPt # not Ruby! 6

ArtistCowboys This code has Person define a pocket for subclasses to use, but an ArtistCowboy wants two pockets, one for each draw method class Person attr_accessor :pocket class Artist < Person # pocket for brush objects def draw # access pocket class Cowboy < Person # pocket for gun objects def draw # access pocket class ArtistCowboy < Artist, Cowboy # not Ruby! 7

Mixins A mixin is (just) a collection of methods Less than a class: no instances of it Languages with mixins (e.g., Ruby modules) typically let a class have one superclass but include any number of mixins Semantics: Including a mixin makes its methods part of the class Exting or overriding in the order mixins are included in the class definition More powerful than helper methods because mixin methods can access methods (and instance variables) on self not defined in the mixin 8

Example module Doubler def double self + self # assume included in classes w/ + class String include Doubler class AnotherPt attr_accessor :x, :y include Doubler def + other ans = AnotherPt.new ans.x = self.x + other.x ans.y = self.y + other.y ans 9

Lookup rules Mixins change our lookup rules slightly: When looking for receiver obj's method m, look in obj's class, then mixins that class includes (later includes shadow), then obj's superclass, then the superclass' mixins, etc. As for instance variables, the mixin methods are included in the same object So usually bad style for mixin methods to use instance variables since a name clash would be like our CowboyArtist pocket problem (but sometimes unavoidable?) 10

The two big ones The two most popular/useful mixins in Ruby: Comparable: Defines <, >, ==,!=, >=, <= in terms of <=> Enumerable: Defines many iterators (e.g., map, find) in terms of each Great examples of using mixins: Classes including them get a bunch of methods for just a little work Classes do not sp their one superclass for this Do not need the complexity of multiple inheritance See the code for some examples 11

Replacement for multiple inheritance? A mixin works pretty well for ColorPt3D: Color a reasonable mixin except for using an instance variable module Color attr_accessor :color A mixin works awkwardly-at-best for ArtistCowboy: Natural for Artist and Cowboy to be Person subclasses Could move methods of one to a mixin, but it is odd style and still does not get you two pockets module ArtistM class Artist < Person include ArtistM class ArtistCowboy < Cowboy include ArtistM 12

Statically-Typed OOP Now contrast multiple inheritance and mixins with Java/C#-style interfaces Important distinction, but interfaces are about static typing, which Ruby does not have So will use Java code after quick introduction to static typing for class-based OOP Sound typing for OOP prevents method missing errors 13

Classes as Types In Java/C#/etc. each class is also a type Methods have types for arguments and result class A { Object m1(example e, String s) { } Integer m2(a foo, Boolean b, Integer i) { } } If C is a (transitive) subclass of D, then C is a subtype of D Type-checking allows subtype anywhere supertype allowed So can pass instance of C to a method expecting instance of D 14

Interfaces are (or were) JustTypes interface Example { void m1(int x, int y); Object m2(example x, String y); } An interface is not a class; it is [er, used to be] only a type Does not contain method definitions, only their signatures (types) Unlike mixins (Changed in Java 8, makes them more like mixins!) Cannot use new on an interface Like mixins 15

Implementing Interfaces A class can explicitly implement any number of interfaces For class to type-check, it must implement every method in the interface with the right type More on allowing subtypes later! Multiple interfaces no problem; just implement everything If class type-checks, it is a subtype of the interface class A implements Example { public void m1(int x, int y) { } public Object m2(example e, String s) { } } class B implements Example { public void m1(int pizza, int beer) { } public Object m2(example e, String s) { } } 16

Multiple interfaces Interfaces provide no methods or fields So no questions of method/field duplication when implementing multiple interfaces, unlike multiple inheritance What interfaces are for: Caller can give any instance of any class implementing I So callee can call methods in I regardless of class So much more flexible type system Interfaces have little use in a dynamically typed language Dynamic typing already much more flexible, with trade-offs we studied 17

Connections Let s now answer these questions: What does a statically typed OOP language need to support required overriding? How is this similar to higher-order functions? Why does a language with multiple inheritance (e.g., C++) not need Java/C#-style interfaces? [Explaining Java s abstract methods / C++ s pure virtual methods] 18

Required overriding Often a class expects all subclasses to override some method(s) The purpose of the superclass is to abstract common functionality, but some non-common parts have no default A Ruby approach: Do not define must-override methods in superclass Subclasses can add it Creating instance of superclass can cause method-missing errors # do not use A.new # all subclasses should define m2 class A def m1 v self.m2 e 19

Static typing In Java/C#/C++, prior approach fails type-checking No method m2 defined in superclass One solution: provide error-causing implementation class A def m1 v self.m2 e def m2 v raise "must be overridden" Better: Use static checking to prevent this error 20

Abstract methods Java/C#/C++ let superclass give signature (type) of method subclasses should provide Called abstract methods or pure virtual methods Cannot creates instances of classes with such methods Catches error at compile-time Indicates intent to code-reader Does not make language more powerful abstract class A { T1 m1(t2 x) { m2(e); } abstract T3 m2(t4 x); } class B exts A { T3 m2(t4 x) { } } 21

Passing code to other code Abstract methods and dynamic dispatch: An OOP way to have subclass pass code to other code in superclass abstract class A { T1 m1(t2 x) { m2(e); } abstract T3 m2(t4 x); } class B exts A { T3 m2(t4 x) { } } Higher-order functions: An FP way to have caller pass code to callee fun f (g,x) = g e fun h x = f((fn y => ), ) 22

No interfaces in C++ If you have multiple inheritance and abstract methods, you do not also need interfaces Replace each interface with a class with all abstract methods Replace each implements interface with another superclass So: Expect to see interfaces only in statically typed OOP without multiple inheritance Not Ruby Not C++ 23