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



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

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

Java Interview Questions and Answers

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

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

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

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

Implementation Aspects of OO-Languages

AP Computer Science Java Subset

Inheritance, overloading and overriding

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

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Chapter 13 - Inheritance

Basic Programming and PC Skills: Basic Programming and PC Skills:

Semantic Analysis: Types and Type Checking

Programming Languages Featherweight Java David Walker

Data Structures and Algorithms Written Examination

Habanero Extreme Scale Software Research Project

CS193j, Stanford Handout #10 OOP 3

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

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Introduction to Data Structures

Comp151. Definitions & Declarations

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

Abstract Class & Java Interface

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Java Programming Language

Pemrograman Dasar. Basic Elements Of Java

Java Application Developer Certificate Program Competencies

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

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

Lab Experience 17. Programming Language Translation

Part I. Multiple Choice Questions (2 points each):

Sources: On the Web: Slides will be available on:

Contents. 9-1 Copyright (c) N. Afshartous

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

Part 3: GridWorld Classes and Interfaces

CMSC 202H. ArrayList, Multidimensional Arrays

Introducing Variance into the Java Programming Language DRAFT

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

CS170 Lab 11 Abstract Data Types & Objects

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

C++ INTERVIEW QUESTIONS

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Java (12 Weeks) Introduction to Java Programming Language

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

CSE 1020 Introduction to Computer Science I A sample nal exam

Rigorous Software Development CSCI-GA

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Stack Allocation. Run-Time Data Structures. Static Structures

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

J a v a Quiz (Unit 3, Test 0 Practice)

Analysis of a Search Algorithm

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Introduction to Programming System Design. CSCI 455x (4 Units)

Lecture 9. Semantic Analysis Scoping and Symbol Table

C++FA 5.1 PRACTICE MID-TERM EXAM

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

LINKED DATA STRUCTURES

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Visualising Java Data Structures as Graphs

Chapter 1 Java Program Design and Development

Introduction to Java

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Moving from CS 61A Scheme to CS 61B Java

Software Engineering Techniques

Practical Session 4 Java Collections

Limitations of Data Encapsulation and Abstract Data Types

7.1 Our Current Model

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

13 Classes & Objects with Constructors/Destructors

Introduction: Abstract Data Types and Java Review

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

An Incomplete C++ Primer. University of Wyoming MA 5310

The Interface Concept

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

PLV Goldstein 315, Tuesdays and Thursdays, 6:00PM-7:50PM. Tuesdays and Thursdays, 4:00PM-5:30PM and 7:50PM 9:30PM at PLV G320

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Chapter 5 Names, Bindings, Type Checking, and Scopes

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

C# and Other Languages

Compile-time type versus run-time type. Consider the parameter to this function:

Lecture Notes on Linear Search

Crash Course in Java

Class 16: Function Parameters and Polymorphism

Chapter 3: Restricted Structures Page 1

Inside the Java Virtual Machine

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

Introduction to Python

Structural Design Patterns Used in Data Structures Implementation

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Transcription:

Interfaces & Java Types Lecture 10 CS211 Fall 2005 Java Interfaces So far, we have mostly talked about interfaces informally, in the English sense of the word An interface describes how a client interacts with a class Method names, argument/return types, fields Java has a construct called interface which can be used formally for this purpose public interface List { Recall: A List Interface public void insert (Object element); public void delete (Object element); public boolean contains (Object element); public int size (); The interface specifies the methods without saying anything about the implementation Matches idea of ADT (Abstract Data Type) Any class that implements List can be stored in a variable of type List Another Java Interface Example void scramble(); boolean move(char d); class IntPuzzle implements IPuzzle { public void scramble() { public int tile(int r, int c) { public boolean move(char d) { Name of interface: IPuzzle A class implements this interface by implementing instance methods as specified in the interface The class may implement other methods as well Interface Notes An interface is not a class! Cannot be instantiated Incomplete specification A class header must assert implements I for Java to recognize that the class implements interface I A class may implement several interfaces: class X implements IPuzzle, IPod { Why an interface construct? Good software engineering Can specify and enforce boundaries between different parts of a team project Can use interface as a type Allows more generic Reduces duplication

Example of Code Duplication Suppose we have two implementations of puzzles: Class IntPuzzle uses an int to hold state Class ArrayPuzzle uses an array to hold state Assume client wants to use both implementations Perhaps for benchmarking both implementations to pick the best one Assume client has a display method to print out puzzles What would the display method look like? Class Client{ IntPuzzle p1 = new IntPuzzle(); ArrayPuzzle p2 = new ArrayPuzzle(); display(p1)display(p2) public static void display(intpuzzle p){ public static void display(arraypuzzle p){ Code duplicated because IntPuzzle and ArrayPuzzle are different Observation Two display methods are needed because IntPuzzle and ArrayPuzzle are different types, and parameter p must be one or the other But the inside the two methods is identical! Code relies only on the assumption that the object p has an instance method tile(int,int). Is there a way to avoid this duplication? Puzzle Client One Solution: Abstract Classes abstract class Puzzle { abstract class IntPuzzle extends Puzzle { public int tile(int r, int c) { class ArrayPuzzle extends Puzzle { public int tile(int r, int c) { public static void display(puzzle p){ Puzzle Client Another Solution: Interfaces class IntPuzzle implements IPuzzle { public int tile(int r, int c) { class ArrayPuzzle implements IPuzzle { public int tile(int r, int c) { Extending vs. Implementing A class can extend just one superclass Multiple inheritance can cause conflicts Example: Which of 2 inherited methods to use when both have identical signatures? But a class can implement multiple interfaces Multiple interfaces don t conflict because there are no implementations To share between two classes Put shared in a common superclass Interfaces cannot contain

More on Interfaces Interface methods Interface methods are implicitly public and abstract No static methods are allowed in interfaces Interface constants Interface constants are public, static, and final Can inherit multiple versions of constants Compiler detects this When this occurs, fully qualified names are required Interface Types IntPuzzle IPuzzle ArrayPuzzle Interface names can be used in type declarations IPuzzle p1, p2; A class that implements the interface is a subtype of the interface type IntPuzzle and ArrayPuzzle are subtypes of IPuzzle IPuzzle is a supertype of IntPuzzle and ArrayPuzzle Interfaces Classes Java Type Hierarchy IPuzzle IPod IRon AClass BClass Unlike Java classes, Java types do not form a tree! A class may implement several interfaces An interface may be implemented by several classes The type hierarchy does form a dag (directed acyclic graph) Static Type vs. Dynamic Type Every variable (more generally, every expression that denotes some kind of data) has a static* or compile-time type Derived from declarations you can see it Known at compile time, without running the program Does not change Every object ever created also has a dynamic or runtime type Obtained when the object is created using new Not known at compile time you can t see it * Warning! No relation to Java keyword static Example int i = 3, j = 4; Integer x = new Integer(i+3*j-1); System.out.println(x.toString()); static type of the variables i,j and the expression i+3*j-1 is int static type of the variable x and the expression new Integer(i+3*j-1) is Integer static type of the expression x.tostring() is String (because tostring() is declared in the class Integer to have return type String) dynamic type of the object created by the execution of new Integer(i+3*j-1) is Integer Reference vs. Primitive Types Reference types Classes, interfaces, arrays E.g.: Integer x: Primitive types int, long, short, byte, boolean, char, float, double (Integer) int value: 13 String tostring() x: 13

Why Both int and Integer? Some data structures work only with reference types (HashMap, ArrayList, Stack,) Primitive types are more efficient for (int i = 0; i < n; i++) { Upcasting and Downcasting Applies to reference types only Used to assign the value of an expression of one (static) type to a variable of another (static) type upcasting: subtype supertype downcasting: supertype subtype Note that the dynamic type does not change! A crucial invariant: If the value of an expression E is an object O then the dynamic type of O is a subtype of the static type of E Example of upcasting: Upcasting Object x = new Integer(13); Static type of expression on rhs is Integer Static type of variable x on lhs is Object Integer is a subtype of Object, so this is an upcast Static type of expression on rhs must be a subtype of static type of variable on lhs compiler checks this Upcasting is always type correct preserves the invariant automatically Example of downcasting: Downcasting Integer x = (Integer)y; Static type of y is Object (say) Static type of x is Integer Static type of expression (Integer)y is Integer Integer is a subtype of Object, so this is a downcast In any downcast, dynamic type of object must be a subtype of static type of cast expression Implies that a runtime check is needed to maintain invariant (and only time it is needed) ClassCastException if failure Is the Runtime Check Necessary? Yes, because dynamic type of object may not be known at compile time void bar() { foo(new Integer(13)); String("x") void foo(object y) { int z = ((Integer)y).intValue(); Upcasting with Interfaces Java allows upcasting: IPuzzle p1 = new ArrayPuzzle(); IPuzzle p2 = new IntPuzzle(); Static types of right-hand side expressions are ArrayPuzzle and IntPuzzle, respectively Static type of left-hand side variables is IPuzzle Rhs static types are subtypes of lhs static type, so this is OK

Why Upcasting? Subtyping and upcasting can be used to avoid duplication Back to puzzle example: you and client agree on interface IPuzzle interface IPuzzle{ void scramble(); boolean move(char d); Puzzle Code using IPuzzle Interface Client class IntPuzzle implements IPuzzle { public int tile(int r, int c) { class ArrayPuzzle implements IPuzzle { public int tile(int r, int c) { Method Dispatch Which tile method is invoked? Depends on dynamic type of object p (IntPuzzle or ArrayPuzzle) We don't know what this dynamic type is, but whatever it is, we know it has a tile method (since any class that implements IPuzzle must have a tile method) Method Dispatch At compile-time Check that the static type of p (namely IPuzzle) has a tile method with the right type signature? No error At runtime Go to the object that is the value of p, find its dynamic type, look up its tile method The compile-time check guarantees that an appropriate tile method exists Note Upcasting and downcasting do not change the object they merely allow it to be viewed at compile time as a different static type Another Use of Upcasting Heterogeneous Data Structures Example: IPuzzle[] pzls = new IPuzzle[9]; pzls[0] = new IntPuzzle(); pzls[1] = new ArrayPuzzle(); An expression pzls[i] is of type IPuzzle Objects created on right hand sides are of subtypes of IPuzzle

Java instanceof Example: if (p instanceof IntPuzzle) { True if dynamic type of p is a subtype of IntPuzzle Usually used to check if a downcast will succeed Example Suppose twist is a method implemented only in IntPuzzle void twist(ipuzzle[] pzls) { for (int i = 0; i < pzls.length; i++) { if (pzls[i] instanceof IntPuzzle) { IntPuzzle p = (IntPuzzle)pzls[i]; p.twist(); Avoid Useless Downcasting Subinterfaces bad void moveall(ipuzzle[] pzls) { for (int i = 0; i < pzls.length; i++) { if (pzls[i] instanceof IntPuzzle) ((IntPuzzle)pzls[i]).move("N"); else ((ArrayPuzzle)pzls[i]).move("N"); Suppose you want to extend the interface to include more methods IPuzzle: scramble, move, tile ImprovedPuzzle: scramble, move, tile, samloyd good void moveall(ipuzzle[] pzls) { for (int i = 0; i < pzls.length; i++) pzls[i].move("n"); Two approaches Start from scratch and write an interface Extend the IPuzzle interface void scramble(); boolean move(char d); interface ImprovedPuzzle extends IPuzzle { void SamLoyd(); IPuzzle is a superinterface of ImprovedPuzzle ImprovedPuzzle is a subinterface of IPuzzle ImprovedPuzzle is a subtype of IPuzzle An interface can extend multiple superinterfaces A class that implements an interface must implement all methods declared in all superinterfaces C A B Interfaces E D G interface C extends A,B { class F extends D implements A { class E extends D implements A,B { F Classes I

Conclusion Interfaces have two main uses Software engineering: good fences make good neighbors Subtyping Subtyping is a central idea in programming languages Inheritance and interfaces are two methods for creating subtype relationships