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

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

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

CS/ENGRD 2110 SPRING 2018

Review Session. CS2110 Prelim #1 3/8/15. Primitive types vs classes. Default values. Wrapper Classes (Boxing) Strings are immutable.

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

CSE 143 Lecture 20. Circle

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

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

Full file at Chapter 2 - Inheritance and Exception Handling

Inheritance and Interfaces

COMP 110/L Lecture 24. Kyle Dewey

ITI Introduction to Computing II

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

Announcements/Follow-ups

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

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

CS159. Nathan Sprague

CS 61B Discussion 5: Inheritance II Fall 2014

PIC 20A Number, Autoboxing, and Unboxing

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CS159. Nathan Sprague

Abstract Classes, Exceptions

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

CS/ENGRD 2110 SPRING 2018

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

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

Polymorphism and Interfaces. CGS 3416 Spring 2018

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

Inheritance and Polymorphism. CS180 Fall 2007

Comp215: Thinking Generically

Chapter 11: Collections and Maps

Today. Reading. Homework. Lecture Notes CPSC 224 (Spring 2012) hashcode() method. Collections class. Ch 9: hw 7 out (due in a week)

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

Casting. References. References

CSCI 136 Data Structures & Advanced Programming. Lecture 12 Fall 2018 Profs Bill & Jon

Introduction to Object-Oriented Programming

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

COMP 110/L Lecture 20. Kyle Dewey

C# and Java. C# and Java are both modern object-oriented languages

CMPSCI 187: Programming With Data Structures. Lecture #23: Linked Lists David Mix Barrington 31 October 2012

CS-202 Introduction to Object Oriented Programming

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

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

CS Programming Language Java. Fall 2004 Sept. 29

CS 520 Theory and Practice of Software Engineering Fall 2018

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

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Abstract Classes Interfaces CSCI 201 Principles of Software Development

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

Software Development (cs2500)

Abstract Classes and Interfaces

CMSC 132: Object-Oriented Programming II. Interface

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Object Oriented Programming. Java-Lecture 11 Polymorphism

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

CSC207 Week 3. Larry Zhang

ITI Introduction to Computing II

Motivations. Chapter 13 Abstract Classes and Interfaces

Java Programming. Abstract classes and Interfaces

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

Chapter 14 Abstract Classes and Interfaces

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

ECE 122. Engineering Problem Solving with Java

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

Inheritance and Polymorphism

CMSC201 Computer Science I for Majors

C20a: Selected Interfaces in Java API

ITI Introduction to Computing II

STATIC, ABSTRACT, AND INTERFACE

CS 520 Theory and Practice of Software Engineering Fall 2017

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Java Comparable interface

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

Chapter 13 Abstract Classes and Interfaces

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

COE318 Lecture Notes Week 8 (Oct 24, 2011)

CSE 143. Lecture 13: Interfaces, Comparable reading: , 16.4, 10.2

Inheritance, Polymorphism, and Interfaces

COMP 110/L Lecture 19. Kyle Dewey

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

Comparing Objects 3/14/16

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

n HW5 out, due Tuesday October 30 th n Part 1: Questions on material we ll cover today n Part 2: BFS using your graph from HW4

Documenting, Using, and Testing Utility Classes

More Relationships Between Classes

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

Credit: The lecture slides are created based on previous lecture slides by Dan Zingaro.

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017

Chapter 2: Java OO II X I A N G Z H A N G

Practice Midterm 1 Answer Key

Informatik II (D-ITET) Tutorial 6

Java Object Oriented Design. CSC207 Fall 2014

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Fundamentals of Object Oriented Programming

Outline. More optimizations for our interpreter. Types for objects

Polymorphism. Arizona State University 1

Transcription:

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

Announcements 2 Attendance for this week s recitation is mandatory! A2 is due Today Get started on A3 a method every other day

A Little Geometry! Abstract Classes Shape x y Square area() size Triangle area() base height Circle area() radius 5

Demo 1: Complete this function Abstract Classes /** Return the sum of the areas of * the shapes in s */ static double sumareas(shape[] s) { 1. Operator instanceof and casting are required 2. Adding new Shape subclasses breaks sumareas

A Partial Solution: Abstract Classes Add method area to class Shape: public double area() { return 0; public double area() { throw new RuntimeException( area not overridden );

Problems not solved Abstract Classes 1. What is a Shape that isn t a Circle, Square, Triangle, etc? What is only a shape, nothing more specific? a.shape s= new Shape(...); Should be disallowed 2. What if a subclass doesn t override area()? a. Can t force the subclass to override it! b. Incorrect value returned or exception thrown.

Solution: Abstract classes Abstract Classes Abstract class Means that it can t be instantiated. public abstract class Shape new Shape() { illegal public double area() { return 0;

Solution: Abstract methods Abstract Classes public abstract class Shape { public abstract double area(); Abstract method Subclass must override. Can also have implemented methods Place abstract method only in abstract class. Semicolon instead of body.

Demo 2: A better solution Abstract Classes We modify class Shape to be abstract and make area() an abstract method. Abstract class prevents instantiation of class Shape Abstract method forces all subclasses to override area()

Abstract Classes, Abstract Methods Abstract Classes 1. Cannot instantiate an object of an abstract class. (Cannot use new-expression) 2. A subclass must override abstract methods.

Interfaces

Problem Interfaces Where is the best place to implement whistle()? Animal Mammal Bird Whistler Human Dog Parrot

No multiple inheritance in Java! Interfaces class Whistler { void breathe() { class Animal { void breathe() { new Human().breathe(); Which breathe() should java run in class Human? class Human extends Animal, Whistler {

Why not make it fully abstract? Interfaces class abstract Whistler { Java doesn t allow this, even abstract void breathe(); though it would work. Instead, Java has another class abstract Animal { construct for this purpose, the abstract void breathe(); interface class Human extends Animal, Whistler {

Solution: Interfaces Interfaces public interface Whistler { void whistle(); int MEANING_OF_LIFE= 42; methods are automatically public and abstract fields are automatically public, static, and final (i.e. constants) class Human extends Mammal implements Whistler { Must implement all methods in the implemented interfaces

Multiple interfaces Interfaces public interface Singer { void singto(human h); Classes can implement several interfaces! They must implement all the methods in those interfaces they implement. class Human extends Mammal implements Whistler, Singer { Must implement singto(human h) and whistle()

Solution: Interfaces Interfaces Interface Whistler offers promised functionality to classes Human and Parrot! Animal Whistler Mammal Bird Human Dog Parrot

Casting to an interface Interfaces Human h= new Human(); Object o= (Object) h; Animal a= (Animal) h; Mammal m= (Mammal) h; Object Animal Singer s= (Singer) h; Whistler w= (Whistler) h; Whistler Mammal Singer All point to the same memory address! Human

Casting to an interface Interfaces Human h= new Human(); Object o= h; Animal a= h; Mammal m= h; Singer s= h; Whistler w= h; Automatic up-cast Forced down-cast Whistler Object Animal Mammal Human Singer

Casting up to an interface automatically Interfaces class Human implements Whistler { void listento(whistler w) {... Human h = new Human(...); Human h1= new Human(...); h.listento(h1); Object Animal Arg h1 of the call has type Human. Its value is being stored in w, which is of type Whistler. Java does an upward cast automatically. It costs no time; it is just a matter of perception. Whistler Mammal Human

Demo 3: Implement Comparable<T> Implement interface Comparable in class Shape: public interface Comparable<T> { /** = 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(t c);

Shape implements Comparable<T> public class Shape implements Comparable<Shape> {... /** */ public int compareto(shape s) { double diff= area() - s.area(); return (diff == 0? 0 : (diff < 0? -1 : +1));

Beauty of interfaces Arrays.sort sorts an array of any class C, as long as C implements interface Comparable<T> without needing to know any implementation details of the class. Classes that implement Comparable: Boolean Byte Double Integer String BigDecimal BigInteger Calendar Time Timestamp and 100 others

String sorting Arrays.sort(Object[] b) sorts an array of any class C, as long as C implements interface Comparable<T>. String implements Comparable, so you can write String[] strings=...;... Arrays.sort(strings); During the sorting, when comparing elements, a String s compareto function is used

And Shape sorting, too! Arrays.sort(Object[] b) sorts an array of any class C, as long as C implements interface Comparable<T>. Shape implements Comparable, so you can write Shape[] shapes=...;... Arrays.sort(shapes); During the sorting, when comparing elements, a Shape s compareto function is used

Abstract Classes vs. Interfaces Abstract class represents something Sharing common code between subclasses Interface is what something can do 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)