CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Similar documents
CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 SPRING 2018

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

CS/ENGRD 2110 SPRING 2018

ITI Introduction to Computing II

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

Inheritance. Transitivity

Lecture 10. Overriding & Casting About

Data Structures And Algorithms

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

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

CS-202 Introduction to Object Oriented Programming

Polymorphism and Interfaces. CGS 3416 Spring 2018

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

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

Polymorphism. return a.doublevalue() + b.doublevalue();

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

Topic 5: Abstract Classes & Interfaces

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

Inheritance, Polymorphism, and Interfaces

Announcements/Follow-ups

Exceptions and Design

CSIS 10B Lab 2 Bags and Stacks

Inheritance and Polymorphism

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

Midterm Exam 2 CS 455, Spring 2011

Super-Classes and sub-classes

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

Introduction to Object-Oriented Programming

Advanced Placement Computer Science. Inheritance and Polymorphism

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

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

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

OBJECT ORİENTATİON ENCAPSULATİON

Java Object Oriented Design. CSC207 Fall 2014

ITI Introduction to Computing II

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

Rules and syntax for inheritance. The boring stuff

MIT AITI Lecture 18 Collections - Part 1

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

ITI Introduction to Computing II

Inheritance and Interfaces

CS 251 Intermediate Programming Inheritance

Inheritance and Polymorphism. CS180 Fall 2007

Inheritance and Polymorphism

CT 229 Object-Oriented Programming Continued

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

CSE 143 Lecture 20. Circle

Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p no multiple inheritance with classes

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Abstract and final classes [Horstmann, pp ] An abstract class is kind of a cross between a class and an interface.

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

CMP Points Total Midterm Spring Version (16 Points) Multiple Choice:

Making New instances of Classes

Informatik II (D-ITET) Tutorial 6

Chapter 14 Abstract Classes and Interfaces

What is Inheritance?

INHERITANCE. Spring 2019

16 Multiple Inheritance and Extending ADTs

Interfaces. Relatedness of types. Interface as a contract. The area and perimeter of shapes 7/15/15. Savitch ch. 8.4

Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010

Solutions to Quiz 1 (March 14, 2016)

Abstract Classes and Interfaces

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

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

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

Interfaces & Generics

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

Subclassing for ADTs Implementation

Page 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Topic 7: Algebraic Data Types

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

C a; C b; C e; int c;

CIS 110: Introduction to computer programming

Prelim 1. Solution. CS 2110, 14 March 2017, 7:30 PM Total Question Name Short answer

== isn t always equal?

Abstract Classes, Exceptions

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Object Oriented Programming. Java-Lecture 11 Polymorphism

Java Primer. CITS2200 Data Structures and Algorithms. Topic 0

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Outline and Reading. The Stack ADT ( 2.1.1) Applications of Stacks ( 2.1.1) Array-based implementation ( 2.1.1) Growable array-based stack ( 1.

Code Reuse: Inheritance

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Csci 102: Sample Exam

COMP 110/L Lecture 24. Kyle Dewey

More Relationships Between Classes

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Transcription:

CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1

Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method equals 2

A Little Geometry! 3 (x, y) Position of a rectangle in the plane is given by its upper-left corner (x, y) Position of a circle in the plane is given by the upper-left corner of its bounding box 3

A Little Geometry! Abstract Classes Shape contains coordinates in the plane. Subclasses declare additional fields and method area. x y Shape Rectangle width height area() base height area() Triangle radius area() Circle 4 4

What is only a Shape, anyway?? Abstract Classes Notice: An object of Shape is not really a shape. à Don t want to allow creation of objects of class Shape! x y Shape Make the class abstract! public abstract class Shape { base height area() Triangle radius area() Syntactic rule: if class C is abstract, the new-expression new C( ) cannot be used! Circle

Writing sumareas in class Shape Abstract Classes /** Return sum of areas of shapes in s */ public static double sumareas(shape[] s) { double sum= 0; for (int k= 0; k < s.length; k= k+1) sum= sum + s[k].area(); return sum; Does this work? Compile-time reference rule says no! Solutions? 1. Cast down to make the call? 2. Make area a method of Shape? a0 x y 5 7 Shape sumareas(shape[]) Circle area() 6 6

Approach 2: define area in Shape Abstract Classes Add method area to class Shape: public double area() { return 0; Use this instead? public double area() { throw new RuntimeException( area not overridden ); Problem: a subclass might forget to override area(). Problem: a subclass might still forget to override area(). 7 7

Approach 3: Make area abstract! (Yay!) Abstract Classes In abstract class Shape, an abstract function area is required of all subclasses: public abstract class Shape { /** Return the area of this shape */ public abstract double area() ; Syntax: If a method has keyword abstract in its declaration, use a semicolon instead of a method body. 8 8

Abstract Summary 1. To make it impossible to create an instance of a class C, make C abstract: public abstract C { 2. In an abstract class, to require each subclass to override method m( ), make m abstract: Abstract Classes Syntax: the program cannot be compiled if C is abstract and program contains a newexpression new C( ) Syntax: the program cannot be compiled if a subclass of an abstract class does not override an abstract method. public abstract int m( ) ; 9 9

Abstract class used to define a type (abstract data type, or ADT) Type: set of values together with operations on them Define type Stack (of ints). Its operations are: isempty() push(k) pop() --return true iff the stack is empty --push integer k onto the Stack --pop the top stack element public abstract class Stack { public abstract boolean isempty(); public abstract void push(int k); public abstract int pop(); Naturally, need specifications 10

Example of Stack subclass: ArrayStack public abstract class Stack { public abstract boolean isempty(); public abstract void push(int k); public abstract int pop(); public class ArrayStack extends Stack { private int n; // stack elements are in private int[] b; // b[0..n-1]. b[0] is bottom /** Constructor: An empty stack of max size s. */ public ArrayStack(int s) {b= new int[s]; public boolean isempty() {return n == 0; public void push(int v) { b[n]= v; n= n+1; Missing tests for errors! Missing specs! public int pop() {n= n-1; return b[n]; 11

Example of Stack subclass: LinkedListStack public abstract class Stack { public abstract boolean isempty(); public abstract void push(int k); public abstract int pop(); public class LinkedListStack extends Stack{ private int n; // number of elements in stack private Node first; // top node on stack /** Constructor: An empty stack */ public LinkedListStack() { public boolean isempty() { public void push(int v) { public int pop() {

Flexibility! public abstract class Stack { public class ArrayStack extends Stack { public class LinkedListStack extends Stack { Store the ptr in a variable of type Stack! /** A class that needs a stack */ public class C { Stack st= new ArrayStack(20); public void m() { st.push(5); Choose an array implementation, max of 20 values Use only methods available in abstract class Stack 13

Flexibility! public abstract class Stack { public class ArrayStack extends Stack { public class LinkedListStack extends Stack { /** A class that needs a stack */ public class C { LinkedListStack(); Stack st= new ArrayStack(20); public void m() { st.push(5); Want to use a linked list instead of an array? Just change the new-expression! 14

Interfaces An interface is like an abstract class all of whose components are public abstract methods. Just have a different syntax We don t tell you immediately WHY Java has this feature, this construct. First let us define the interface and see how it is used. The why will become clear as more and more examples are shown. (an interface can have a few other kinds of components, but they are limited. For now, it is easiest to introduce the interface by assuming it can have only public abstract methods and nothing else. Go with that for now!) 15

Interfaces An interface is like an abstract class all of whose components are public abstract methods. Just have a different syntax public abstract class Stack { public abstract boolean isempty(); public abstract void push(int k); public abstract int pop(); Here is an abstract class. Contains only public abstract methods public interface Stack { public abstract boolean isempty(); public abstract void push(int k); public abstract int pop(); Here is how we declare it as an interface 16

Interfaces public abstract class Stack { public abstract boolean isempty(); public abstract void push(int k); public abstract int pop(); public interface Stack { boolean isempty(); void push(int k); int pop(); Methods must be public and abstract, so we can leave off those keywords. Extend a class: class StackArray extends Stack { Implement an interface: class StackArray implements Stack { 17

A start at understanding use of interfaces Have this class hierarchy: class Animal { class Mammal extends Animal {... class Bird extends Animal { class Human extends Mammal {. class Dog extends Mammal { class Parrot extends Bird { Object Animal Mammal Bird 18 Human Dog Parrot

A start at understanding use of interfaces Humans and Parrots can speak. Other Animals cannot. public void speak(string w) { System.out.println(w); Object We need a way of indicating that classes Human and Parrot have this method speak Animal Mammal Bird 19 Human Dog Parrot

A start at understanding use of interfaces public interface Speaker { void speak(string w); public class Human extends Mammal implements Speaker { public void speak(string w) { System.out.println(w); Speaker (similarly for Parrot) Mammal Object Animal Bird 20 Human Dog Parrot

Here s what an object of class Human looks like public interface Speaker {void speak(string w); public class Human extends Mammal implements Speaker { public void speak(string w) { System.out.println(w); Usual drawing of object Human@1 Animal Mammal Draw it this way Object Animal Mammal Add interface dimension Speaker 21 Human Human

Here s what an object of class Human looks like Human h= new Human(); Object ob= h; Animal a= (Animal) ob; Mammal m= h; Speaker s= h; Object h, ob, a, m, and w all point to the same object. The object can be (and is) cast to any partition in it: h, ob, a, m, and w. Animal Upward casts: can be implicit; inserted by Java 22 Mammal Human Speaker Downward casts: must be explicit

A real use of interface: sorting Consider an array of Shapes: want to sort by increasing area Consider an array of ints: want to sort them in increasing order Consider an array of Dates: want to put in chronological order We don t want to write three different sorting procedures! The sorting procedure should be the same in all cases. What differs is how elements of the array are compared. So, write ONE sort procedure, tell it the function to be used to compare elements. To do that, we will use an interface. 23

Interface Comparable Package java.lang contains this interface public interface Comparable { /** = a negative integer if this object < c, = 0 if this object = c, = a positive integer if this object > c. Throw a ClassCastException if c can t be cast to the class of this object. */ int compareto(object c); 24

Real example: Comparable We implement Comparable in class Shape public abstract class Shape implements Comparable { /** Return area of this shape */ public abstract double area() ; /** See previous slide*/ public int compareto(object c) { Shape s= (Shape) c; double diff= area() s.area(); return diff == 0? 0 : (diff < 0? -1 : 1); If c can t be cast to Shape, a ClassCastException is thrown

Arrays.sort has this method /** Sort array b. Elements of b must implement interface Comparable. Its method compareto is used to determine ordering of elements of b. */ Arrays.sort(Object[] b) Shape implements Comparable, so we can write: // Store an array of values in shapes Shape[] shapes=...;... Arrays.sort(shapes); 26

What an object of subclasses look like public abstract class Shape implements Comparable { public class Circle extends Shape { public class Rectangle extends Shape { When sort procedure is comparing elements of a Shape array, each element is a Shape. Sort procedure views it from Comparable perspective! Object Object Comparable Comparable Shape Shape 27 Circle Rectangle

Abstract Classes vs. Interfaces Abstract class represents something Share common code between subclasses Interface is what something can do. Defines an abstract data type A contract to fulfill Software engineering purpose Similarities: Can t instantiate Must implement abstract methods Later we ll use interfaces to define abstract data types (e.g. List, Set, Stack, Queue, etc) 28 28

Operator instanceof vs getclass 29 <object> instanceof <class-name> is true iff <object> has a partition named <class-name> h instanceof Object h.getclass() == Object.class h instanceof Animal h.getclass() == Animal.class h instanceof Cat h.getclass() == Cat.class h instanceof PhD is true is false is true is false is true is true is false h a0 a0 Object getclass() equals(object) age 5 tostring() purrs() Animal Animal isolder(animal) Cat

Approach 1: Cast down to make the call Abstract Classes double sum= 0; for (int k= 0; k < s.length; k= k+1) { if (sh[k] instanceof Circle) sum= sum + ((Circle) sh[k]).area(); else if (sh[k] instanceof Rectangle) return sum;! or "? sum= sum + ((Rectangle) sh[k]).area(); 1. Code is ugly 2. Code doesn t age well 30 30