Programming Languages and Techniques (CIS120)

Similar documents
Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120)

OO)terminology) Every)(Java))object)is)an)instance)of)some)class)

Programming Languages and Techniques (CIS120)

CIS 120 Midterm II March 31, 2017 SOLUTIONS

CIS 120 Midterm II November 8, Name (printed): Pennkey (login id):

Programming Languages and Techniques (CIS120)

CIS 120 Midterm II November 16, Name (printed): Pennkey (login id):

CIS 120 Midterm II November 8, 2013 SOLUTIONS

Programming Languages and Techniques (CIS120)

Name: Pennkey: CIS 120 Midterm II November 18, 2011

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

CIS 120 Midterm II November 16, 2012 SOLUTIONS

Programming Languages and Techniques (CIS120)

Introduction to Programming Using Java (98-388)

Derived and abstract data types. TDT4205 Lecture 15

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

G Programming Languages - Fall 2012

Programming Languages and Techniques (CIS120)

Midterms Save the Dates!

Abstract Data Types (ADT) and C++ Classes

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Java Classes & Primitive Types

EXPRESSIONS AND ASSIGNMENT CITS1001

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

An introduction to Java II

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

CIS 110: Introduction to Computer Programming

An Introduction to C++

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Goal of lecture. Object-oriented Programming. Context of discussion. Message of lecture

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

PREPARING FOR THE FINAL EXAM

Practice exam for CMSC131-04, Fall 2017

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Computer Science II Data Structures

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

Building Java Programs

Java Classes & Primitive Types

CS 320: Concepts of Programming Languages

Index COPYRIGHTED MATERIAL

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

Building Java Programs

CS 231 Data Structures and Algorithms, Fall 2016

COE318 Lecture Notes Week 4 (Sept 26, 2011)

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Variables and Operators 2/20/01 Lecture #

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Programming Languages and Techniques (CIS120e)

Lecture 3. Lecture

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

EECS168 Exam 3 Review

Physics 2660: Fundamentals of Scientific Computing. Lecture 3 Instructor: Prof. Chris Neu

CIS 120 Midterm II March 29, 2013 SOLUTIONS

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

ob-ject: to feel distaste for something Webster's Dictionary

Programming Languages and Techniques (CIS120)

CS171:Introduction to Computer Science II

Compiler construction 2009

CIS 120 Midterm II November 7, Name (printed): Pennkey (login id):

6.170 Lecture 7 Abstract Data Types MIT EECS

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

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Programming Languages and Techniques (CIS120)

ITI Introduction to Computing II

Objects and Classes. Basic OO Principles. Classes in Java. Mark Allen Weiss Copyright 2000

Announcements. 1. Forms to return today after class:

CSE 431S Type Checking. Washington University Spring 2013

Lecture 3 Tao Wang 1

Object-Oriented Programming Concepts

Object typing and subtypes

The Java Programming Language

Transcription:

Programming Languages and Techniques (CIS120) Lecture 22 March 14 th, 2016 Object Oriented Programming in Java

Java Bootcamp tonight Announcements Monday, March 14 from 6-8pm in Levine 101 (Wu & Chen) Midterm 2 March 22 nd, 6:15-8:15PM, location TBA Make- up exam, Wed March 23 rd, 9-11AM Sign up for make- up exam on course website by March 20 th HW5: Java Programming Will be available soon Due: Tuesday, March 29 th at 11:59pm (after the exam) CIS120 2

Midterm 2 Focus of exam: Programming in OCaml with higher- order functions and mutable state Homeworks 4 (queues) and 5 (GUI) Through Wednesday's lecture everything from first exam (1-10) mutable & immutable records (11-13) ASM (14) options (15), queues, deques and tail recursion (16) object encoding, local state (17) and reactive programming (18) comparisons between OCaml and Java (19 & 20) Practice exams on website Old exams were held later in the course (after HW 6) Not covered this time: writing Java code, Java arrays, Java subtyping and dynamic dispatch, Java ASM

Object- Oriented Programming in Java

OO terminology Object: a structured collection of fields (aka local state or instance variables) and methods Class: a template for creating objects The class of an object specifies the types and initial values of its local state (fields) the set of operations that can be performed on the object (methods) one or more constructors: code that is executed when the object is created (optional) Every (Java) object is an instance of some class CIS120 5

"Objects" in OCaml (* The type of counter objects *) type counter = { inc : unit -> int; dec : unit -> int; (* Create a counter object *) let new_counter () : counter = let r = {contents = 0 in { inc = (fun () -> r.contents <- r.contents + 1; r.contents); dec = (fun () -> r.contents <- r.contents - 1; r.contents) Why is this an object? Encapsulated local state only visible to the methods of the object Object is defined by what it can do local state does not appear in the interface There is a way to construct new object values that behave similarly CIS120 6

Objects in Java public class Counter { class name class declaration private int r; instance variable public Counter () { r = 0; public int inc () { r = r + 1; return r; public int dec () { r = r - 1; return r; constructor methods public class Main { public static void main (String[] args) { Counter c = new Counter(); object creation and use constructor invocation System.out.println( c.inc() ); CIS120 method call 7

Encapsulating local state public class Counter { r is private private int r; public Counter () { r = 0; public int inc () { r = r + 1; return r; public int dec () { r = r - 1; return r; constructor and methods can refer to r other parts of the public class Main { program can only access public static void public members main (String[] args) { Counter c = new Counter(); System.out.println( c.inc() ); CIS120 method call 8

Encapsulating local state Visibility modifiers make the state local by controlling access Basically: public : accessible from anywhere in the program private : only accessible inside the class Design pattern first cut: Make all fields private Make constructors and non- helper methods public (There are a couple of other protection levels protected and package protected. The details are not important at this point.) CIS120 9

What is the value of ans at the end of this program? Counter x = new Counter(); x.inc(); int ans = x.inc(); 1. 1 2. 2 3. 3 4. NullPointerException Answer: 2 public class Counter { private int r; public Counter () { r = 0; public int inc () { r = r + 1; return r;

What is the value of ans at the end of this program? Counter x; x.inc(); int ans = x.inc(); 1. 1 2. 2 3. 3 4. NullPointerException Answer: NPE public class Counter { private int r; public Counter () { r = 0; public int inc () { r = r + 1; return r;

What is the value of ans at the end of this program? Counter x = new Counter(); x.inc(); Counter y = x; y.inc(); int ans = x.inc(); 1. 1 2. 2 3. 3 4. NullPointerException public class Counter { private int r; public Counter () { r = 0; public int inc () { r = r + 1; return r; Answer: 3

OO comparison OCaml Explicitly create objects using a record of higher order functions and hidden state Flexibility through composition: objects can only implement one interface (i.e. button = widget * label_controller * notifier_controller). Java (and C, C++, C#) Primitive notion of object creation (classes, with fields, methods and constructors) Flexibility through extension: Subtyping allows objects to implement multiple interfaces (i.e. button <: widget) CIS120 17

Interfaces Working with objects abstractly

Objects in OCaml vs. Java (* The type of point objects *) type point = { getx : unit -> int; gety : unit -> int; move : int*int -> unit; (* Create an "object" with hidden state: *) type position = { mutable x: int; mutable y: int; let new_point () : point = let r = {x = 0; y=0 in { getx = (fun () -> r.x); gety = (fun () -> r.y); move = (fun (dx,dy) -> r.x <- r.x + dx; r.y <- r.y + dy) Type is separate from the implementation public class Point { private int x; private int y; public Point () { x = 0; y = 0; public int getx () { return x; public int gety () { return y; public void move (int dx, int dy) { x = x + dx; x = x + dx; Class specifies both type and implementation of object values

Interfaces Give a type for an object based on what it does, not on how it was constructed Describes a contract that objects must satisfy Example: Interface for objects that have a position and can be moved public interface Displaceable { public int getx(); public int gety(); public void move(int dx, int dy); No fields, no constructors, no method bodies!

Implementing the interface A class that implements an interface provides appropriate definitions for the methods specified in the interface That class fulfills the contract implicit in the interface methods required to satisfy contract public class Point implements Displaceable { private int x, y; public Point(int x0, int y0) { x = x0; y = y0; public int getx() { return x; public int gety() { return y; public void move(int dx, int dy) { x = x + dx; y = y + dy; interfaces implemented

Another implementation public class Circle implements Displaceable { private Point center; private int radius; public Circle(Point initcenter, int initradius) { center = initcenter; radius = initradius; public int getx() { return center.getx(); public int gety() { return center.gety(); public void move(int dx, int dy) { center.move(dx, dy); Objects with different Delegation: move the local state can satisfy circle by moving the the same interface center

Another implementation class ColoredPoint implements Displaceable { private Point p; private Color c; ColoredPoint (int x0, int y0, Color c0) { p = new Point(x0,y0); c = c0; public void move(int dx, int dy) { p.move(dx, dy); public int getx() { return p.getx(); public int gety() { return p.gety(); public Color getcolor() { return c; Flexibility: Classes may contain more methods than interface requires

Interfaces are types Can declare variables of interface type void m(displaceable d) { Can call method with any Displaceable argument obj.m(new Point(3,4)); obj.m(new ColoredPoint(1,2,Color.Black));... but m can only operate on d according to the interface d.move(-1,1); d.getx() 0.0 d.gety() 3.0 d.getcolor() Doesn't type check

Using interface types Interface variables can refer (during execution) to objects of any class implementing the interface Point, Circle, and ColoredPointare all subtypes of Displaceable Displaceable d0, d1, d2; d0 = new Point(1, 2); d1 = new Circle(new Point(2,3), 1); d2 = new ColoredPoint(-1,1, red); d0.move(-2,0); d1.move(-2,0); d2.move(-2,0); d0.getx() -1.0 d1.getx() 0.0 d2.getx() -3.0 Class that created the object value determines what move function is called.

Abstraction The interface gives us a single name for all the possible kinds of moveable things. This allows us to write code that manipulates arbitrary Displaceable objects, without caring whether it s dealing with points or circles. class DoStuff { public void moveitalot (Displaceable s) { s.move(3,3); s.move(100,1000); s.move(1000,234651); public void dostuff () { Displaceable s1 = new Point(5,5); Displaceable s2 = new Circle(new moveitalot(s1); moveitalot(s2); Point(0,0),100);

Multiple interfaces An interface represents a point of view but there can be multiple valid points of view Example: Geometric objects All can move (all are Displaceable) Some have Color (are Colored)

Colored interface Contract for objects that that have a color Circles and Points don t implement Colored ColoredPoints do public interface Colored { public Color getcolor();

ColoredPoints public class ColoredPoint implements Displaceable, Colored { Point center; private Color color; public Color getcolor() { return color;

Recap Object: A collection of related fields (or instance variables) Class: A template for creating objects, specifying types and initial values of fields code for methods optionally, a constructor that is run each time a new object is created from the class Interface: A signature for objects, describing a collection of methods that must be providedby classes that implement the interface Object Type: Either a class or an interface (meaning this object was created from a class that implements this interface )

Java Core Language differences between OCaml and Java

Expressions vs. Statements OCaml is an expression language Every program phrase is an expression (and returns a value) The special value () of type unit is used as the result of expressions that are evaluated only for their side effects Semicolon is an operator that combines two expressions (where the left- hand one returns type unit) Java is a statement language Two- sorts of program phrases: expressions (which compute values) and statements (which don t) Statements are terminated by semicolons Any expression can be used as a statement (but not vice- versa)

Types As in OCaml, every Java expression has a type The type describes the value that an expression computes Expression form Example Type Variable reference x Declared type of variable Object creation new Counter () Class of the object Method call c.inc() Return type of method Equality test x == y boolean Assignment x = 5 don t use as an expression!!

Type System Organization primitive types (values stored directly in the stack) structured types (a.k.a. reference types values stored in the heap) OCaml int, float, char, bool, tuples, datatypes, records, functions, arrays (objects encoded as records of functions) Java generics a list List<A> int, float, double, char, boolean, objects, arrays (records, tuples, datatypes, strings, first- class functions are a special case of objects) abstract types module types (signatures) interfaces public/private modifiers

Arithmetic & Logical Operators OCaml Java =, == == equality test <>,!=!= inequality >, >=, <, <= >, >=, <, <= comparisons + + addition (and string concatenation) - - subtraction (and unary minus) * * multiplication / / division mod % remainder (modulus) not! logical not && && logical and (short- circuiting) logical or (short- circuiting)

New: Operator Overloading The meaning of an operator is determined by the types of the values it operates on Integer division 4/3 1 Floating point division 4.0/3.0 1.3333333333333333 Automatic conversion 4/3.0 1.3333333333333333 Overloading is a general mechanism in Java we ll see more of it later

Equality like OCaml, Java has two ways of testing reference types for equality: pointer equality o1 == o2 deep equality o1.equals(o2) every object provides an equals method that does the right thing depending on the class of the object Normally, you should use == to compare primitive types and.equals to compare objects

Strings String is a built in Java class Strings are sequences of characters "" "Java" "3 Stooges" " 富士山 " + means String concatenation (overloaded) "3" + " " + "Stooges" "3 Stooges" Text in a String is immutable (like OCaml) but variables that store strings are not String x = "OCaml"; String y = x; Can't do anything to x so that y changes The.equals method returns true when two strings contain the same sequence of characters

What is the value of ans at the end of this program? String x = "CIS 120"; String z = "CIS 120"; boolean ans = x.equals(z); 1. true 2. false 3. NullPointerException Answer: true This is the preferred method of comparing strings.

What is the value of ans at the end of this program? String x1 = "CIS "; String x2 = "120"; String x = x1 + x2; String z = "CIS 120"; boolean ans = (x == z); 1. true 2. false 3. NullPointerException Answer: false Even though x and z both contain the characters CIS 120, they are stored in two different locations in the heap.