CS/ENGRD 2110 fall 2017 Lecture 7: Interfaces and Abstract Classes

Slides:



Advertisements
Similar presentations
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Advertisements

ABSTRACT CLASSES AND INTERFACES. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method without.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Review of classes and subclasses M fast through this material, since by now all have seen it in CS100 or the Java bootcamp First packages Then classes.
1 Lecture 06(Abstract Classes)Lecture 9 Abstract Classes Overview  Abstract Classes: A Definition.  Declaring Abstract Classes.  Abstract Methods: A.
Abstract classes and Interfaces. Abstract classes.
Lecture 3 Casting Abstract Classes and Methods Interfaces.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Chapter 3 Introduction to Collections – Stacks Modified
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
CS/ENGRD 2110 SPRING 2015 Lecture 6: Consequence of type, casting; function equals 1.
CS/ENGRD 2110 FALL 2014 Lecture 6: Consequence of type, casting; function equals 1.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Inheritance Notes Chapter 6 1. Inheritance  you know a lot about an object by knowing its class  for example what is a Komondor? 2
Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
CS/ENGRD 2110 FALL 2015 Lecture 6: Consequence of type, casting; function equals 1.
Object Oriented Programming in Java Habib Rostami Lecture 7.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
CS/ENGRD 2110 SPRING 2016 Lecture 6: Consequence of type, casting; function equals 1.
Lecture 5:Interfaces and Abstract Classes
Modern Programming Tools And Techniques-I
Final exam: Period B: Thursday, 13 May, 9:00-11:30AM, Barton East
CS/ENGRD 2110 Spring 2017 Lecture 7: Interfaces and Abstract Classes
Chapter 15 Abstract Classes and Interfaces
Java and OOP Part 5 – More.
Inheritance ITI1121 Nour El Kadri.
Abstract Classes and Interfaces
Abstract Classes and Interfaces
Stacks.
CS/ENGRD 2110 fall 2017 Lecture 7: Interfaces and Abstract Classes
Sorry these slides weren’t available last evening!
CS/ENGRD 2110 Fall 2017 Lecture 6: Consequence of type, casting; function equals
The fattest knight at King Arthur's round table was Sir Cumference
CS/ENGRD 2110 Spring 2018 Lecture 7: Interfaces and Abstract Classes
Interfaces and Inheritance
CMSC 341 Lecture 5 Stacks, Queues
Lesson 2: Building Blocks of Programming
More inheritance, Abstract Classes and Interfaces
Stacks, Queues, and Deques
Polymorphism Phil Tayco San Jose City College Slide version 1.1
Week 6 Object-Oriented Programming (2): Polymorphism
CS/ENGRD 2110 Fall 2018 The fattest knight at King Arthur's round table was Sir Cumference. He acquired his size from too much pi. Lecture 6: Consequence.
Abstract classes, Interfaces
CS/ENGRD 2110 FALL 2016 Lecture 7: Interfaces and Abstract Classes
CS18000: Problem Solving and Object-Oriented Programming
Stacks Abstract Data Types (ADTs) Stacks
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Generics, Lambdas, Reflections
CS/ENGRD 2110 Spring 2019 Lecture 7: Interfaces and Abstract Classes
Chapter 14 Abstract Classes and Interfaces
CS/ENGRD 2110 Spring 2019 Lecture 6: Consequence of type, casting; function equals
Java Programming Language
Review of Previous Lesson
Review of Previous Lesson
Chapter 13 Abstract Classes and Interfaces Part 01
Abstract Classes and Interfaces
Abstract Classes and Interfaces
Presentation transcript:

CS/ENGRD 2110 fall 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110

READ CAREFULLY & THOROUGHLY Announcements A2 is due Sunday night (16 September) Prelim 1 is two weeks away! GO TO THE WEBPAGE: http://www.cs.cornell.edu/courses/cs2110/2018fa/exams.html Study Guide When you take the exam (where comes later) Half of you will take the exam at 5:30! The other half at 7:30! Whom to contact about conflicts READ CAREFULLY & THOROUGHLY 2

Go back to Lecture 6 & talk about equals

Operator instanceof and function getClass ..@54 s Object Shape Rect ..@54 What is s instanceof Rect ? What is s.getClass() ? Square 4

Where are we? You watched 15 minutes of videos in preparation for this lecture. You learned about abstract classes and interfaces. Reason for asking you to watch it: You now have seen the technical details and have a basic understanding. We can now give examples and discuss things at greater depth than if you had not watched the videos. 5

A Little Geometry! (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 6

A Little Geometry! Shape x y Shape contains coordinates in the plane. Abstract Classes Shape x y Shape contains coordinates in the plane. Subclasses declare additional fields and the method area. Rectangle width height area() Triangle base height area() Circle radius area() Encourage the students to download the code for this online The goal is to incorporate an area method for all shapes Note that on this slide (and others), to simplify formatting, we show a variable as its name following by underlining, and we may put the value in the underline place (as done in one case here) x,y are coordinates that are for all shapes. Each subclass has its own relevant fields. Explain that Circle, Square, and Triangle all have different area() functions but Shape does not have one 7

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

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? Use instanceof and cast down to make the call? (next slide) Make area a method of Shape? Show them the code and how each of the subclasses have a function area but not in superclass Shape. Doesn’t work. Try writing it as below. Point out how ugly the casting makes the function private static double sumAreas(Shape[] s){ int sum= 0; for (int i = 0; i < s.length; i++) { if (s] instanceof Square) { sum+= ((Square) s]).area(); } else if (s] instanceof Triangle) { sum+= ((Triangle) s]).area(); } else if (s] instanceof Circle) { sum+= ((Circle) s]).area(); } return total; Discussion notes regarding the function: Not very extensible: if you try to add another subclass All methods using Shapes need to change Bugs appear if more subclasses are added and methods aren’t fixed Casting is ugly, verbose, and has potential for runtime errors Also! All different types of shapes have area, but superclass Shape doesn’t have a function area - a bit strange 9

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) sum= sum + ((Rectangle) sh[k]).area(); } return sum; 👍🏽 or 👎 ? Show them the code and how each of the subclasses have a function area but not in superclass Shape Point out how ugly the casting makes the function private static double sumAreas(Shape[] s){ int sum= 0; for (int i = 0; i < s.length; i++) { if (s] instanceof Square) { sum+= ((Square) s]).area(); } else if (s] instanceof Triangle) { sum+= ((Triangle) s]).area(); } else if (s] instanceof Circle) { sum+= ((Circle) s]).area(); } return total; Discussion notes regarding the function: Not very extensible: if you try to add another subclass All methods using Shapes need to change Bugs appear if more subclasses are added and methods aren’t fixed Casting is ugly, verbose, and has potential for runtime errors Also! All different types of shapes have area, but superclass Shape doesn’t have a function area - a bit strange 1. Code is ugly 2. Code doesn’t age well 10

Approach 2: define area in Shape Abstract Classes Add method area to class Shape: public double area() { return 0; } Problem: a subclass might forget to override area(). Problem: a subclass might still forget to override area(). Use this instead? public double area() { throw new RuntimeException( “area not overridden”); } Try to solve the casting problem: Ask for ideas. Solve our earlier problem - makes sumAreas(..) simple and clean, but has its own host of issues: Subclasses of Shape have to remember to override - easy to lose track of, cause bugs down the line Shapes that aren’t subclasses have 0 area, which would normally be incorrect Now add the RuntimeException: Gets even closer. Now we can’t call getArea on Shapes that aren’t subclasses. Still, subclasses of Shape have to remember to override - easy to lose track of, cause bugs down the line Makes a lot more runtime errors – compile time (syntax) errors are easier to catch and fix 11

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. 12

Abstract Summary Abstract Classes 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: public abstract int m(…) ; Syntax: the program cannot be compiled if C is abstract and program contains a new-expres-sion new C(…) Syntax: the program cannot be compiled if a subclass of an abstract class does not override an abstract method. Why? Java requires this so that the following doesn’t happen. If subclasses didn’t override the abstract method, we could have a situation where the method gets called but it has no implementation to use If we could instantiate an object of an abstract class and tried to call one of the abstract methods, it would have no implementation to use 13

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() --return true iff the stack is empty push(k) --push integer k onto the Stack pop() --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 14

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;} public int pop() {n= n-1; return b[n]; } } Missing tests for errors! Missing specs! 15

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() {return n == 0;} public void push(int v) { prepend v to list} public int pop() { …} } Missing tests for errors! Missing specs!

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

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

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!) 19

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 20

Interfaces Extend a class: Implement an interface: 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 { … } 21

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 Mammal Human Parrot Dog Bird Animal

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

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); (similarly for Parrot) Object Mammal Human Parrot Dog Bird Animal Speaker

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); } } Human@1 Animal Mammal Human Usual drawing of object Mammal Human Animal Object Draw it this way Add interface dimension Speaker

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; 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. Mammal Human Animal Object Speaker Upward casts: can be implicit; inserted by Java 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.

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); }

Real example: Comparable We implement Comparable in class Shape public abstract class Shape { … /** Return area of this shape */ public abstract double area() ; } implements Comparable /** 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 of 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);

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! Shape Circle Object Comparable Shape Rectangle Object Comparable

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) 32