Haskell s Take on the Expression Problem

Size: px
Start display at page:

Download "Haskell s Take on the Expression Problem"

Transcription

1 Haskell s Take on the Expression Problem Ralf Lämmel Universität Koblenz-Landau, Software Languages Team, Koblenz, Germany joint work with Oleg Kiselyov Fleet Numerical Meteorology and Oceanography Center, Monterey, CA 1

2 Elevator speech Suppose you have some data variants (say apples and oranges ) and you have some operations on such data (say drink and squeeze ), how would you go about the design of data and operations so that you can hopefully add new data variants and new operations later on? 2

3 Expression problem: Why the name? Consider such data: Expressions as in programming languages: Literals Addition Consider such operations: Pretty print expressions Evaluate expressions Consider such extension scenarios: Add another expression form Cases for all existing operations must be added. Add another operation Cases for all existing expression forms must be added. The name goes back to Phil Wadler who defined the expression problem in an sent to mailing lists and individuals in November

4 Expression problem: What problem? In basic OO programming: It is easy to add new data variants. It is hard to add new operations. In basic functional programming: It is easy to add new operations. It is hard to add new data variants. In OO programming with visitors:... It is easy to add new operations. It is hard to add new data variants. 4

5 Data extensibility based on simple inheritance class Expr: The base class of all expression forms Virtual methods: method prettyprint: operation for pretty-printing method evaluate: operation for expression evaluation Subclasses: class Lit: The expression form of "literals" class Add: The expression form of "addition"... Data extensibility 5

6 The class rooting all data variants /** * The base class of all expression forms */ public abstract class Expr { /* * Operation for pretty printing */ public abstract String prettyprint(); /* * Operation for expression evaluation */ public abstract int evaluate(); Beware of code bloat! 6

7 /** * The expression form of "literals" (i.e., constants) */ public class Lit extends Expr { private int info; public int getinfo() { return info; public void setinfo(int info) { this.info = info; public String prettyprint() { return Integer.toString(getInfo()); public int evaluate() { return getinfo(); Beware of code bloat! A class for a data variant 7

8 /** * The expression form of "addition" */ public class Add extends Expr { That is, another data variant but with the same operations. private Expr left, right; public Expr getleft() { return left; public void setleft(expr left) { this.left = left; public Expr getright() { return right; public void setright(expr right) { this.right = right; public String prettyprint() {... public int evaluate() { return getleft().evaluate() + getright().evaluate(); Beware of code bloat! 8

9 /** * The expression form of "negation" */ public class Neg extends Expr { That is, yet another data variant but, again, with the same operations. private Expr expr; public Expr getexpr() { return expr; public void setexpr(expr expr) { this.expr = expr; public String prettyprint() { return "-(" + getexpr().prettyprint() + ")"; public int evaluate() { return - getexpr().evaluate(); Beware of code bloat! 9

10 Operation extensibility based on public data and pattern matching data type Expr: The union of all expression forms Public constructors: Lit: The expression form of "literals" Add: The expression form of "addition" Functions defined by pattern matching on Expr: function prettyprint: operation for pretty-printing function evaluate: operation for expression evaluation... Operation extensibility 10

11 Algebraic data types of Haskell are closed! module Data where -- A data type of expression forms 2 constructor components data Exp = Lit Int Add Exp Exp Algebraic data type Constructor Constructor component Constructor 11

12 A new module can be designated to each new operation. module PrettyPrinter where import Data Argument type -- Operation for pretty printing Result type side effect prettyprint :: Exp -> IO () prettyprint (Lit i) = putstr (show i) prettyprint (Add l r) = do prettyprint l; putstr " + "; prettyprint r Operation defined by case discrimination 12

13 Another operation; another module. module Evaluator where import Data -- Operation for expression evaluation evaluate :: Exp -> Int evaluate (Lit i) = i evaluate (Add l r) = evaluate l + evaluate r 13

14 Operation extensibility based on visitors class Expr: The base class of all expression forms Subclasses as before. Virtual methods: Accept a visitor ( apply an operation ) Visitors: class PrettyPrinter: operation for pretty-printing class Evaluator: operation for expression evaluation... Operation extensibility 14

15 Domain operations are no longer hosted in domain classes. /** * The base class of all expression forms */ public abstract class Expr { /* * Accept a visitor (i.e., apply an operation) */ public abstract <R> R accept(visitor<r> v); 15

16 Requires folklore knowledge on design patterns. /** * A concrete visitor describe a concrete operation on expressions. * There is one visit method per type in the class hierarchy. */ public abstract class Visitor<R> { public abstract R visit(lit x); public abstract R visit(add x); public abstract R visit(neg x); 16

17 One visitor-enabled data variant. /** * The expression form of "literals" (i.e., constants) */ public class Lit extends Expr { private int info; public int getinfo() { return info; public void setinfo(int info) { this.info = info; public <R> R accept(visitor<r> v) { return v.visit(this); 17

18 /** * The expression form of "addition" */ public class Add extends Expr { Another visitor-enabled data variant. private Expr left, right; public Expr getleft() { return left; public void setleft(expr left) { this.left = left; public Expr getright() { return right; public void setright(expr right) { this.right = right; public <R> R accept(visitor<r> v) { return v.visit(this); Beware of code bloat! 18

19 Yet another visitor-enabled data variant. /** * The expression form of "negation" */ public class Neg extends Expr { private Expr expr; public Expr getexpr() { return expr; public void setexpr(expr expr) { this.expr = expr; public <R> R accept(visitor<r> v) { return v.visit(this); Beware of code bloat! 19

20 /** * Operation for pretty printing */ public class PrettyPrinter extends Visitor<String> { public String visit(lit x) { return Integer.toString(x.getInfo()); public String visit(add x) { return x.getleft().accept(this) + " + " + x.getright().accept(this); public String visit(neg x) { return "- (" + x.getexpr().accept(this) + ")"; Beware of code bloat! An operation represented as a concrete visitor. 20

21 Another operation represented as a concrete visitor. /** * Operation for expression evaluation */ public class Evaluator extends Visitor<Integer> { public Integer visit(lit x) { return x.getinfo(); public Integer visit(add x) { return x.getleft().accept(this) + x.getright().accept(this); public Integer visit(neg x) { return - x.getexpr().accept(this); Beware of code bloat! 21

22 A final Java experiment: poor men s full extensibility We use instanceof tests and casts to dispatch functionality on data. We use a specific exception and try-catch blocks to extend operations. We encapsulate operations in objects so that extensions are self-aware. This is approach is weakly typed. In particular, there is no guarantee that we have covered all cases. 22

23 Domain classes are nothing but data capsules. public abstract class Expr { public class Lit extends Expr { private int info; public int getinfo() { return info; public void setinfo(int info) { this.info = info; public class Add extends Expr { private Expr left, right; public Expr getleft() { return left; public void setleft(expr left) { this.left = left; public Expr getright() { return right; public void setright(expr right) { this.right = right; 23

24 public class EvaluatorBase { We simulate pattern matching by instanceof and cast. public int evaluate(expr e) { if (e instanceof Lit) { Lit l = (Lit)e; return l.getinfo(); if (e instanceof Add) { Add a = (Add)e; return evaluate(a.getleft()) + evaluate(a.getright()); throw new FallThrouhException(); We anticipate failure of such operations as a means to compose them. 24

25 public class EvaluatorExtension extends EvaluatorBase { An extended operation first attempts the basic implementation. public int evaluate(expr e) { try { return super.evaluate(e); catch (FallThrouhException x) { if (e instanceof Neg) { Neg n = (Neg)e; return -evaluate(n.getexpr()); throw new FallThrouhException(); Recursive calls are properly dispatched through this to the extended operation. 25

26 The notion of extensibility The initial system I: Provides operations o 1,, o m. Handles data variants d 1,, d n. Consider any number of extensions e 1,, e k : e i could be a data extension: Introduce a new data variant. Provide cases for all existing operations. e i could be an operation extension: Introduce a new operation. Provide cases for all existing data variants. Any extension can be factored into such primitive ones. The fully extended system e k ( (e 1 (I))) 26

27 More on extensibility Code-level extensibility: Extensions can be modeled as code units. Existing code units are never edited or cloned. Separate compilation: The extensions are compiled separately. Statically type-checked extensibility: The extension are statically type-checked separately. 27

28 Solutions of the expression problem Open classes in more dynamic languages (Smalltalk, etc.) Extensible predicates in Prolog (code-level extensibility only) Java, C# & Co. Clever encodings (Torgersen, ECOOP 2004) AOP-like Open classes (introductions).net-like partial classes (code-level extensibility only) Expanders (Warth et al., OOPSLA 2006) JavaGI (Wehr et al., ECOOP 2007)... 28

29 Haskell supernatural type system at work: full extensibility based on type classes Open (extensible) datatypes Haskell 98 is sufficient at this point! Designate one type constructor per original data constructor. Use a type class to describe the open union of data constructors. Open (extensible) functions Designate one type class per operation. Designate one instance of that class per data variant. See also Lämmel and Ostermann s GPCE '06 paper: Software extension and integration with type classes 29

30 The initial data variants data Exp = Lit Int Add Exp Exp module DataBase where Non-extensible Extensible -- Data variants for literals and addition data Lit = Lit Int data Add l r = Add l r One designated data type per data variant -- The open union of data variants class Exp x instance Exp Lit instance Exp (Add l r) Type class ( set of types ) Type-class instances 30

31 The initial data variants data Exp = Lit Int Add Exp Exp module DataBase where Non-extensible Extensible -- Data variants for literals and addition data Lit = Lit Int data Add l r = Add l r -- The open union of data variants That s not precise! class Exp x instance Exp Lit instance Exp (Add l r) 31

32 The initial data variants data Exp = Lit Int Add Exp Exp module DataBase where Non-extensible Extensible -- Data variants for literals and addition data Lit = Lit Int data Add l r = Add l r -- The open union of data variants Constraints for operands of add class Exp x instance Exp Lit instance (Exp l, Exp r) => Exp (Add l r) 32

33 The initial data variants data Exp = Lit Int Add Exp Exp module DataBase where Non-extensible Extensible -- Data variants for literals and addition data Lit = Lit Int data (Exp l, Exp r) => Add l r = Add l r -- The open union of data variants Constraints for operands of add class Exp x instance Exp Lit instance (Exp l, Exp r) => Exp (Add l r) 33

34 Fact sheet on single-parameter type classes Type class = nominal set of types with common operations (Type-class) instances add a type to the set To be seen! define operations specifically for the type at hand Comparison to Java/C# interfaces Interfaces are implemented with classes. Instances may be added retroactively. 34

35 The initial pretty printing operation prettyprint :: Exp -> IO () prettyprint (Lit i) = putstr (show i) prettyprint (Add l r) = do prettyprint l; putstr " + "; prettyprint r module PrettyPrinterBase where import DataBase Non-extensible Extensible -- Operation for pretty printing class Exp x => PrettyPrint x where prettyprint :: x -> IO () instance PrettyPrint Lit where prettyprint (Lit i) = putstr (show i) A type class for pretty-printing all expressions The operation is a member of the type class instance (PrettyPrint l, PrettyPrint r) => PrettyPrint (Add l r) where prettyprint (Add l r) = do prettyprint l; putstr " + "; prettyprint r 35

36 The initial evaluation operation evaluate :: Exp -> Int evaluate (Lit i) = i evaluate (Add l r) = evaluate l + evaluate r module EvaluatorBase where Non-extensible Extensible import DataBase -- Operation for expression evaluation class Exp x => Evaluate x where evaluate :: x -> Int instance Evaluate Lit where evaluate (Lit i) = i 36 instance (Evaluate l, Evaluate r) => Evaluate (Add l r) where evaluate (Add l r) = evaluate l + evaluate r

37 A data extension module DataExtension where import DataBase import PrettyPrinterBase import EvaluatorBase -- Data extension for negation data Exp x => Neg x = Neg x instance Exp x => Exp (Neg x) -- Extending operation for pretty printing instance PrettyPrint x => PrettyPrint (Neg x) where prettyprint (Neg x) = do putstr "(- "; prettyprint x; putstr ")" -- Extending operation for expression evaluation instance Evaluate x => Evaluate (Neg x) where evaluate (Neg x) = 0 - evaluate x 37

38 An operation extension: class Show x where show :: x -> String show expressions in prefix notation module OperationExtension1 where import DataBase import DataExtension Type class Show is predefined. instance Show Lit where show (Lit i) = "Lit " ++ show i instance (Exp x, Exp y, Show x, Show y) => Show (Add x y) where show (Add x y) = "Add (" ++ show x ++ ") (" ++ show y ++ ")" instance (Exp x, Show x) => Show (Neg x) where show (Neg x) = "Neg (" ++ show x ++ ")" 38

39 Another operation extension: treealize expression terms module OperationExtension2 where > totree $ Add (Lit 1) (Lit 2) Node "Add" [Node "Lit" ["1"], Node "Lit" ["2"]] import Data.Tree import DataBase import DataExtension class ToTree x where totree :: x -> Tree String instance ToTree Lit where totree (Lit i) = Node "Lit" [] instance (Exp x, Exp y, ToTree x, ToTree y) => ToTree (Add x y) where totree (Add x y) = Node "Add" [totree x, totree y] instance (Exp x, ToTree x) => ToTree (Neg x) where totree (Neg x) = Node "Neg" [totree x] 39

40 Noteworthy Haskell constructs and idioms covered. (This is merely a check list: all of these constructs and idioms should have been explained through the previous slides.) Algebraic data types Pattern matching (Data) constructors Type constructors Constrained type constructors (Single-parameter) type classes Type-class instances Instance constraints Type-class-bounded polymorphism Super-class constraints Type-class-based open data types Modules Haskell 98 has bee sufficient so far! 40

41 Summary The Expression Problem and software extension Dimensions of software extensibility Data extensibility Operation extensibility Major qualities Discussed Code-level extensibility (Soft) static type checking Separate compilation / deployment Not discussed Performance ( No distributed fat ) Configurability 41

Homework 11 Due Wednesday, 12/1/10

Homework 11 Due Wednesday, 12/1/10 Homework 11 Due Wednesday, 12/1/10 Please turn in your homework solutions online at http://www.dci.pomona.edu/tools-bin/cs131upload.php before the beginning of class on the due date. 1. (10 points) Subtyping

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Katja Laboratory Abstract Syntax Trees in Java with Katja

Katja Laboratory Abstract Syntax Trees in Java with Katja Katja Laboratory Abstract Syntax Trees in Java with Katja Lecture Compiler and Language Processing Tools 2011 Jan Schäfer (slides by Jean-Marie Gaillourdet) Software Technology Group TU Kaiserslautern

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CSC324 Principles of Programming Languages

CSC324 Principles of Programming Languages CSC324 Principles of Programming Languages http://mcs.utm.utoronto.ca/~324 November 21, 2018 Last Class Types terminology Haskell s type system Currying Defining types Value constructors Algebraic data

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Winter /22/ Hal Perkins & UW CSE H-1 CSE P 501 Compilers Implementing ASTs (in Java) Hal Perkins Winter 2008 1/22/2008 2002-08 Hal Perkins & UW CSE H-1 Agenda Representing ASTs as Java objects Parser actions Operations on ASTs Modularity

More information

Functional OO Programming. Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Functional OO Programming. Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Functional OO Programming Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Let s say we know OOP. What s functional programming? Functional programming focuses on functions as abstractions

More information

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1

CSE P 501 Compilers. Implementing ASTs (in Java) Hal Perkins Autumn /20/ Hal Perkins & UW CSE H-1 CSE P 501 Compilers Implementing ASTs (in Java) Hal Perkins Autumn 2009 10/20/2009 2002-09 Hal Perkins & UW CSE H-1 Agenda Representing ASTs as Java objects Parser actions Operations on ASTs Modularity

More information

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

A Pattern Language To Visitors

A Pattern Language To Visitors A Pattern Language To Visitors Yun Mai and Michel de Champlain Department of Electrical and Computer Engineering Concordia University {y mai, michel@ece.concordia.ca Abstract Since Gamma et al. first published

More information

JavaGI: Generalized Interfaces for Java

JavaGI: Generalized Interfaces for Java JavaGI: Generalized Interfaces for Java Stefan Wehr Peter Thiemann Ralf Lämmel August 2, 2007, ECOOP Berlin 1 / 14 Motivation Need different Java extensions to solve the following problems: Problem: Update

More information

Reflection (in fact, Java introspection)

Reflection (in fact, Java introspection) Reflection (in fact, Java introspection) Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Elevator speech So programs are programs and data is data. However, programs can be represented

More information

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

The Sun s Java Certification and its Possible Role in the Joint Teaching Material The Sun s Java Certification and its Possible Role in the Joint Teaching Material Nataša Ibrajter Faculty of Science Department of Mathematics and Informatics Novi Sad 1 Contents Kinds of Sun Certified

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Extensibility and Modularity in Programming Languages

Extensibility and Modularity in Programming Languages FB Informatik, Programmiersprachen und Softwaretechnik Extensibility and Modularity in Programming Languages Seminar, WS 2017/18 17.10.2017 Kick-off meeting 2 Introduction INTRODUCTION Basic research questions

More information

(Algebraically oriented) domain modeling in Haskell

(Algebraically oriented) domain modeling in Haskell (Algebraically oriented) domain modeling in Haskell Ralf Lämmel Software Languages Team Faculty of Computer Science University of Koblenz-Landau Acknowledgment: This is joint work with Magne Haveraaen,

More information

CSE 401/M501 Compilers

CSE 401/M501 Compilers CSE 401/M501 Compilers ASTs, Modularity, and the Visitor Pattern Hal Perkins Autumn 2018 UW CSE 401/M501 Autumn 2018 H-1 Agenda Today: AST operations: modularity and encapsulation Visitor pattern: basic

More information

Homework 6. What To Turn In. Reading. Problems. Handout 15 CSCI 334: Spring, 2017

Homework 6. What To Turn In. Reading. Problems. Handout 15 CSCI 334: Spring, 2017 Homework 6 Due 11 April Handout 15 CSCI 334: Spring, 2017 What To Turn In Please hand in work in two pieces, one for the Problems and one for the Programming (Partner Optional): Problems: Turn in handwritten

More information

Reflective Visitor Pattern

Reflective Visitor Pattern Reflective Visitor Pattern Yun Mai and Michel de Champlain Department of Electrical and Computer Engineering Concordia University {y mai, michel@ece.concordia.ca Abstract The Visitor pattern wraps associated

More information

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

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance

More information

Syntax and Grammars 1 / 21

Syntax and Grammars 1 / 21 Syntax and Grammars 1 / 21 Outline What is a language? Abstract syntax and grammars Abstract syntax vs. concrete syntax Encoding grammars as Haskell data types What is a language? 2 / 21 What is a language?

More information

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413

Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 13: Types and Type-Checking 19 Feb 07 Semantic Analysis Last time: Semantic errors related to scopes Symbol tables Name resolution This lecture:

More information

Advanced features of Functional Programming (Haskell)

Advanced features of Functional Programming (Haskell) Advanced features of Functional Programming (Haskell) Polymorphism and overloading January 10, 2017 Monomorphic and polymorphic types A (data) type specifies a set of values. Examples: Bool: the type of

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

JAVA MOCK TEST JAVA MOCK TEST II

JAVA MOCK TEST JAVA MOCK TEST II http://www.tutorialspoint.com JAVA MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Java Framework. You can download these sample mock tests at your

More information

APCS Unit 5 Exam. Assuming all four classes have a default constructor, which of the following statements would result in an error from the compiler?

APCS Unit 5 Exam. Assuming all four classes have a default constructor, which of the following statements would result in an error from the compiler? APCS Unit 5 Exam Name 1. Suppose we had a superclass called Fruit. The subclasses of this superclass are Apple, Orange, and Banana. Consider the following reference variable declarations. Fruit f; Banana

More information

Compaq Interview Questions And Answers

Compaq Interview Questions And Answers Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not

More information

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming

More information

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

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

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 17: Types and Type-Checking 25 Feb 08 CS 412/413 Spring 2008 Introduction to Compilers 1 What Are Types? Types describe the values possibly

More information

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

(800) Toll Free (804) Fax   Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days Course Description This course introduces the Java programming language and how to develop Java applications using Eclipse 3.0. Students learn the syntax of the Java programming language, object-oriented

More information

Java Programming. Atul Prakash

Java Programming. Atul Prakash Java Programming Atul Prakash Java Language Fundamentals The language syntax is similar to C/ C++ If you know C/C++, you will have no trouble understanding Java s syntax If you don't, it will be easier

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

CSE 431S Type Checking. Washington University Spring 2013

CSE 431S Type Checking. Washington University Spring 2013 CSE 431S Type Checking Washington University Spring 2013 Type Checking When are types checked? Statically at compile time Compiler does type checking during compilation Ideally eliminate runtime checks

More information

Advances in Programming Languages

Advances in Programming Languages T O Y H Advances in Programming Languages APL8: Multiparameter Type Classes, Constructor Classes Ian Stark School of Informatics The University of Edinburgh Thursday 4 February Semester 2 Week 4 E H U

More information

5/23/2015. Core Java Syllabus. VikRam ShaRma

5/23/2015. Core Java Syllabus. VikRam ShaRma 5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5

More information

Object Model. Object Oriented Programming Spring 2015

Object Model. Object Oriented Programming Spring 2015 Object Model Object Oriented Programming 236703 Spring 2015 Class Representation In Memory A class is an abstract entity, so why should it be represented in the runtime environment? Answer #1: Dynamic

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

C++ Inheritance and Encapsulation

C++ Inheritance and Encapsulation C++ Inheritance and Encapsulation Private and Protected members Inheritance Type Public Inheritance Private Inheritance Protected Inheritance Special method inheritance 1 Private Members Private members

More information

Inheritance - Assignment5

Inheritance - Assignment5 Inheritance - Assignment5 Expr objects What they look like? Inheritance hierarchy Inheriting instance variables and methods How to do method lookup? Polymorphism Abstract classes Complex objects Recursive

More information

User-Defined Algebraic Data Types

User-Defined Algebraic Data Types 72 Static Semantics User-Defined Types User-Defined Algebraic Data Types An algebraic data type declaration has the general form: data cx T α 1... α k = K 1 τ 11... τ 1k1... K n τ n1... τ nkn introduces

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

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

CS-XXX: Graduate Programming Languages. Lecture 22 Class-Based Object-Oriented Programming. Dan Grossman 2012 CS-XXX: Graduate Programming Languages Lecture 22 Class-Based Object-Oriented Programming Dan Grossman 2012 PL Issues for OOP? OOP lets you: 1. Build some extensible software concisely 2. Exploit an intuitive

More information

Type Hierarchy. Lecture 6: OOP, autumn 2003

Type Hierarchy. Lecture 6: OOP, autumn 2003 Type Hierarchy Lecture 6: OOP, autumn 2003 The idea Many types have common behavior => type families share common behavior organized into a hierarchy Most common on the top - supertypes Most specific at

More information

More on Objects in JAVA TM

More on Objects in JAVA TM More on Objects in JAVA TM Inheritance : Definition: A subclass is a class that extends another class. A subclass inherits state and behavior from all of its ancestors. The term superclass refers to a

More information

Semantic analysis. Compiler Construction. An expression evaluator. Examples of computations. Computations on ASTs Aspect oriented programming

Semantic analysis. Compiler Construction. An expression evaluator. Examples of computations. Computations on ASTs Aspect oriented programming Semantic analysis Compiler Construction source code scanner semantic analysis Computations on ASTs Aspect oriented programming tokens AST with attributes Lennart Andersson parser code generation Revision

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

9 Working with the Java Class Library

9 Working with the Java Class Library 9 Working with the Java Class Library 1 Objectives At the end of the lesson, the student should be able to: Explain object-oriented programming and some of its concepts Differentiate between classes and

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

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

Don t Believe the Hype. CS152: Programming Languages. Lecture 21 Object-Oriented Programming. Class-based OOP. So what is OOP? Don t Believe the Hype CS152: Programming Languages Lecture 21 Object-Oriented Programming Dan Grossman Spring 2011 OOP lets you: 1. Build some extensible software concisely 2. Exploit an intuitive analogy

More information

CSE Lecture 3: Objects 2 September Nate Nystrom University of Texas at Arlington

CSE Lecture 3: Objects 2 September Nate Nystrom University of Texas at Arlington CSE 3302 Lecture 3: Objects 2 September 2010 Nate Nystrom University of Texas at Arlington Administration Out of town this afternoon thru Monday HW1 due next Thursday 9/9 Types Last time: strongly typed

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems Basics of OO Programming with Java/C# Basic Principles of OO Abstraction Encapsulation Modularity Breaking up something into smaller, more manageable pieces Hierarchy Refining through levels of abstraction

More information

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

Code reuse through polymorphic variants

Code reuse through polymorphic variants Code reuse through polymorphic variants Jacques Garrigue November 8, 2000 Abstract Their support for code reuse has made object-oriented languages popular. However, they do not succeed equally in all areas,

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

.jj file with actions

.jj file with actions Hand-coded parser without actions Compiler Construction Computations on ASTs Lennart Andersson Revision 2011-02-07 2011 void stmt() { switch(token) { case IF: accept(if); expr(); accept(then); stmt();

More information

Objects, Subclassing, Subtyping, and Inheritance

Objects, Subclassing, Subtyping, and Inheritance Objects, Subclassing, Subtyping, and Inheritance Brigitte Pientka School of Computer Science McGill University Montreal, Canada In these notes we will examine four basic concepts which play an important

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Introduce C# as Object Oriented programming language. Explain, tokens,

Introduce C# as Object Oriented programming language. Explain, tokens, Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

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

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures Chapter 5: Procedural abstraction Proper procedures and function procedures Abstraction in programming enables distinction: What a program unit does How a program unit works This enables separation of

More information

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking Agenda COMP 181 Type checking October 21, 2009 Next week OOPSLA: Object-oriented Programming Systems Languages and Applications One of the top PL conferences Monday (Oct 26 th ) In-class midterm Review

More information

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

Typed Scheme: Scheme with Static Types

Typed Scheme: Scheme with Static Types Typed Scheme: Scheme with Static Types Version 4.1.1 Sam Tobin-Hochstadt October 5, 2008 Typed Scheme is a Scheme-like language, with a type system that supports common Scheme programming idioms. Explicit

More information

Object Model. Object Oriented Programming Winter

Object Model. Object Oriented Programming Winter Object Model Object Oriented Programming 236703 Winter 2014-5 Class Representation In Memory A class is an abstract entity, so why should it be represented in the runtime environment? Answer #1: Dynamic

More information

Data types à la carte. Wouter Swierstra Dutch HUG 25/8/10

Data types à la carte. Wouter Swierstra Dutch HUG 25/8/10 Data types à la carte Wouter Swierstra Dutch HUG 25/8/10 Expressions data Expr where Add :: Expr -> Expr -> Expr Val :: Int -> Expr eval :: Expr -> Int eval (Val x) = x eval (Add l r) = eval l + eval r

More information

Lecture 16: Object Programming Languages

Lecture 16: Object Programming Languages 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

More information

6.005 Elements of Software Construction Fall 2008

6.005 Elements of Software Construction Fall 2008 MIT OpenCourseWare http://ocw.mit.edu 6.005 Elements of Software Construction Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.005 elements

More information

Project Overview. 1 Introduction. 2 A quick introduction to SOOL

Project Overview. 1 Introduction. 2 A quick introduction to SOOL CMSC 22600 Autumn 2016 Compilers for Computer Languages Handout 1 October 6, 2016 Project Overview 1 Introduction The project for the course is to implement a small object-oriented programming language,

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points. Java for Non Majors Final Study Guide April 26, 2017 The test consists of 1. Multiple choice questions 2. Given code, find the output 3. Code writing questions 4. Code debugging question 5. Short answer

More information

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming Exam 1 Prep Dr. Demetrios Glinos University of Central Florida COP3330 Object Oriented Programming Progress Exam 1 is a Timed Webcourses Quiz You can find it from the "Assignments" link on Webcourses choose

More information

Visitors. Move functionality

Visitors. Move functionality Visitors Compiler Construction Visitor pattern, Semantic analysis Lennart Andersson How to modularize in Java (or any other OO language) if we do not have access to AOP mechanisms? Revision 2011-02-08

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

Week 7. Statically-typed OO languages: C++ Closer look at subtyping C++ & Subtyping Week 7 Statically-typed OO languages: C++ Closer look at subtyping Why talk about C++? C++ is an OO extension of C Efficiency and flexibility from C OO program organization from Simula

More information

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance? CS6501 - Internet programming Unit- I Part - A 1 Define Java. Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look

More information

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent

More information

Polymorphic (Generic) Programming in Java

Polymorphic (Generic) Programming in Java Polymorphic (Generic) Programming in Java We have used the fact that Java classes are arranged as a tree with the built in class Object at the root to write generic or polymorphic code such as the following

More information

Dynamic Class Methods in Jav a 1

Dynamic Class Methods in Jav a 1 Dynamic Class Methods in Jav a 1 Christian Heinlein Dept. of Computer Structures, University of Ulm, Germany heinlein@informatik.uni ulm.de Abstract The concept of dynamic class methods in Java, constituting

More information

Example: Haskell algebraic data types (1)

Example: Haskell algebraic data types (1) Example: Haskell algebraic data types (1) Type declaration: data Number = Exact Int Inexact Float Set of values: Each Number value consists of a tag, together with either an Integer variant (if the tag

More information

Making New instances of Classes

Making New instances of Classes Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using

More information

Java for Non Majors Spring 2018

Java for Non Majors Spring 2018 Java for Non Majors Spring 2018 Final Study Guide The test consists of 1. Multiple choice questions - 15 x 2 = 30 points 2. Given code, find the output - 3 x 5 = 15 points 3. Short answer questions - 3

More information

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 1 Problem Ralph owns the Trinidad Fruit Stand that sells its fruit on the street, and he wants to use a computer

More information

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Java Classes Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

Java and OOP. Part 5 More

Java and OOP. Part 5 More Java and OOP Part 5 More 1 More OOP More OOP concepts beyond the introduction: constants this clone and equals inheritance exceptions reflection interfaces 2 Constants final is used for classes which cannot

More information

Maximum Grade: 5 points out of 10 of the exam.

Maximum Grade: 5 points out of 10 of the exam. Systems Programming Audiovisual Systems Engineering, Communications Systems Engineering, Telecommunication Technologies Engineering and Telematics Engineering Degrees Leganés, May 20th, 2014. Duration:

More information