Interfaces, and Polymorphism Sections 8.4, 8.1. Outcomes n Create a polymorphic function for Lists  and other interfaces n Recognize, write, and implement.

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

Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
ABSTRACT CLASSES AND INTERFACES. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method without.
AbstractClassesInterfacesPolymorphism1 Abstract Classes, Interfaces, Polymorphism Barb Ericson Georgia Tech April 2010.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
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,
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 21 / 2008 Instructor: Michael Eckmann.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
CS 106 Introduction to Computer Science I 04 / 28 / 2010 Instructor: Michael Eckmann.
Writing methods. Calling Methods nameOfMethod(parameters) if method returns something, use that value Math.pow(2, 3) returns 8 System.out.println(Math.pow(2,
Interfaces besides classes, Java recognizes another type, an interface interface is used to completely shield off all implementation from the programmer.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-4: Interfaces reading: self-check: exercises: #11.
UML Basics & Access Modifier
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Lecture 3 Casting Abstract Classes and Methods Interfaces.
CS 307 Fundamentals of Computer ScienceInterfaces and Abstract Classes 1 Topic 7 Interfaces and Abstract Classes “I prefer Agassiz in the abstract, rather.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Writing Static Methods Up until now, we have been USING (calling) static methods that other people have written. Now, we will start CREATING our own static.
VARIABLES Programmes work by manipulating data placed in memory. The data can be numbers, text, objects, pointers to other memory areas, and more besides.
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.
EE 422C Interfaces Day 5. 2 Announcements SVN has Project 2. –Partly due next week. –SVN update to get it in your repository. See Piazza for Grocery List.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
Side effects A side effect is anything that happens in a method other than computing and/or returning a value. Example: public class hello { public int.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Creating a GUI Class An example of class design using inheritance and interfaces.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Project 2: Using Variables and Expressions. 222 Project 2 Overview For this project you will work with three programs Circle Paint Ideal_Weight What.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
OOP Basics Classes & Methods (c) IDMS/SQL News
Interfaces & Sub-types Weiss sec Scenario Instructor says: “Implement a class IntegerMath with two methods pow and fact with the following signatures:
Building Java Programs Interfaces reading: , 16.4.
1 More About Derived Classes and Inheritance Chapter 9.
Inheritance Sections 8.4, 8.1.
Methods Attributes Method Modifiers ‘static’
A tree set Our SearchTree class is essentially a set.
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
Wrapper Classes ints, doubles, and chars are known as primitive types, or built-in types. There are no methods associated with these types of variables.
Abstract Data Types Chapter 1.
Lesson 2: Building Blocks of Programming
A tree set Our SearchTree class is essentially a set.
Implementing Non-Static Features
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Lecture 16 - Interfaces Professor Adams.
Chapter 14 Abstract Classes and Interfaces
Review: libraries and packages
2009 Test Key.
Winter 2019 CMPE212 5/25/2019 CMPE212 – Reminders
with Polymorphism and Lambda Expressions
Presentation transcript:

Interfaces, and Polymorphism Sections 8.4, 8.1

Outcomes n Create a polymorphic function for Lists  and other interfaces n Recognize, write, and implement interfaces n Make a class sortable by implementing the Comparable<> interface n BONUS: Add different ways of sorting by implementing the Comparator<> interface

Similar Classes n Separate classes can have similar actions  ArrayList & LinkedList »add an item, remove an item, ask if empty, get an item from a given position, … n But they are completely different data types  can’t use an ArrayList method on a LinkedList  but the LinkedList version of that method would have exactly the same code in the body

ArrayList vs. LinkedList n Only difference is “Array”  “Linked”  and that’s only in the header!  the bodies are exactly the same p.v. printArrayList( ArrayList l) { Sopln(“List is:”); for (String s : l) { Sopln(“\t” + s); } Sopln(); } p.v. printLinkedList( LinkedList l) { Sopln(“List is:”); for (String s : l) { Sopln(“\t” + s); } Sopln(); } See SillyDuplication.java

Calling AL/LL Methods n Arguments must match parameters ArrayList al = new ArrayList (); LinkedList ll = new LinkedList (); … printArrayList(al); // OK printLinkedList(ll); // OK printArrayList(ll);// NOT OK printLinkedList(al);// NOT OK  errors: »required ArrayList, found LinkedList »required LinkedList, found ArrayList

“List” Actions n ArrayList & LinkedList have same methods  add(_), remove(_), isEmpty(), get(_), …  also listIterator() n All these methods are “List” actions  things we want to do with a list n It’d be nice if we could write one method to deal with both kinds of lists  turns out we can!

Polymorphic printList Method n One method that works for both types public void printList(List l) { System.out.println(“List is:”); System.out.println(“List is:”); for (String s : l) { for (String s : l) { System.out.println(“\t” + s); System.out.println(“\t” + s); } System.out.println(); System.out.println();}  called “polymorphic” (= many shapes) n Works because Java knows what Lists do See ListsAreLists.java

Calling List Methods n Both kinds match List parameters ArrayList al = new ArrayList (); LinkedList ll = new LinkedList (); … printList(al); // OK printList(ll); // OK  no errors! »printList is expecting to be given a List »ArrayLists are Lists »LinkedLists are Lists

Polymorphic Variables n Parameters are variables  we can have List variables other places, too List al = new ArrayList (); List ll = new LinkedList (); … printList(al); // OK printList(ll); // OK n But! No such thing as a List object List al = new List (); java.util.list is abstract; cannot be instantiated

What is java.util.List n It’s what’s called an interface  a list of public methods without bodies n It’s a list of things an object could do  but doesn’t say how it would do them n Every List has certain methods defined  add(_), remove(_), get(_), listIterator(), …  but each kind of List does them its own way »ArrayList one way; LinkedList another way google java List to see what methods a List must have

Why Use Interfaces? n We can say what needs doing without saying how it needs to be done  because we mostly don’t care how it’s done  (e.g.) we need a class we can use as a list »this class says it can be used as a list, so let’s use it  don’t get stuck with one class »make an interface & let anyone implement it »use new & better classes as they come along (it’s much easier to add new things)(it’s much easier to add new things) See StringList.java and StringListDemo.java

Interface Declaration public interface InterfaceName { Public_Constant_Declarations… Public_Constant_Declarations… Public_Method_Headers… Public_Method_Headers…} n Very much like a class definition  interface instead of class  methods all public »none of them have bodies!  public constants allowed, too

Interface n Tell Java that group of actions goes together  name the group of actions  say what the actions are  do not say how to do them »different kinds of things may do them different ways public interface Measurable { public double getArea(); public double getArea(); public double getPerimeter(); public double getPerimeter();} See Measurable.java

Using an Interface n Tell method to expect a Measurable object  can use any Measurable method for that object »getArea or getPerimeter public double roundness(Measurable m) { return 4 * Math.PI * m.getArea() / Math.pow(m.getPerimeter(), 2); return 4 * Math.PI * m.getArea() / Math.pow(m.getPerimeter(), 2);}  cannot use any other methods! (*) »we don’t know what other methods it might have (*) not exactly true, but pretty close! See MeasuringStuff.java

Using Measurable Objects n Suppose Circle is Measurable Circle c = new Circle(10.0); System.out.println(“Roundness of c is ” + roundness(c));  c has getArea and getPerimeter methods… »because Circles are Measurables  …so method works just fine  similarly for Rectangles Rectangle r = new Rectangle(10.0, 20.0); System.out.println(“Roundness of r is ” + roundness(r)); Roundness of c is 1.0 Roundness of r is

Exercise n Declare an interface named Playable that has the following methods:  void play()  void play(int numTimes)  double playLength()

Making Classes Measurable n Need to know that a class is Measurable  it’s not enuf to just have the methods  need to tell Java that we have the methods n Done in the class declaration  an implements clause (compare: throws clause) public class Circle implements Measurable { … } public class Rectangle implements Measurable { … }  tells Java they have getArea & getPerimeter »don’t lie! Java will catch you out

The Circle Implementation public class Circle implements Measurable { private double radius; private double radius; public Circle(double r) { radius = r; } public Circle(double r) { radius = r; } public double getRadius(){ return radius; } public double getRadius(){ return radius; } public double getCircumference() { return 2 * Math.PI * radius; } public double getCircumference() { return 2 * Math.PI * radius; } public double getDiameter(){ return 2 * radius; } public double getDiameter(){ return 2 * radius; } public double getArea() { return Math.PI * Math.pow(radius, 2); } public double getArea() { return Math.PI * Math.pow(radius, 2); } public double getPerimeter (){ return getCircumference(); } public double getPerimeter (){ return getCircumference(); }}  says it implements Measurable, then does »has other methods, too – but that’s OK See Circle.java

Annotation n NetBeans will notice methods that implement the Measurable interface  will ask you to annotation  Please do public double getArea() { return Math.PI * Math.pow(radius, 2); public double getPerimeter (){ return getCircumference(); } »NOTE: only on the methods named in Measurable public double getDiameter(){ return 2 * radius; }

Overriding Interface Methods n Interface says that class has the method  does not say how the method works n Class says how the method works says that this method is the same as the one from the interface »so computer can tell if you said it wrong n The two must match exactly public double getArea();// from Measurable public double getArea() { … } // from Circle Actually, the parameter names can be different….

The Rectangle Implementation public class Rectangle implements Measurable { private double length, width; private double length, width; public Rectangle(double l, double w) { length = l; width = w; } public Rectangle(double l, double w) { length = l; width = w; } public double getLength(){ return length; } public double getLength(){ return length; } public double getWidth(){ return width; } public double getWidth(){ return public double getArea() { return length * width; } public double getArea() { return length * public double getPerimeter (){ return 2 * (length + width); } public double getPerimeter (){ return 2 * (length + width); }}  says it implements Measurable, then does »the implementations are different than for Circles See Rectangle.java

Exercise n Write a Square class that implements the Measurable interface  it has an edgeLength (double)  area is edgeLength squared  perimeter is four times edgeLength

Non-Interface Methods n Class may have methods that are not part of the interface  Rectangle: getHeight & getWidth  Circle: getRadius & getCircumference n Polymorphic parameters/variables cannot use those methods  can only use interface methods

What’s OK? n Methods you can ask for depend on the variable, not the object Circle c = new Circle(10); c.getPerimeter(); c.getArea(); c.getRadius(); c.getCircumference(); Rectangle r = new Rectangle(10, 20); r.getPerimeter(); r.getArea(); r.getHeight(); r.getWidth(); Measurable m = new Circle(10); m.getPerimeter(); m.getArea(); m.getRadius(); m.getCircumference();

Compile-Time Method Checking n Try to make sure program won’t crash  make it as safe as we can (no guarantees!) n Asking a Rectangle for its radius would cause a crash n Measurable could be a Rectangle n Asking a Measurable for its radius could cause a crash

Run-Time Method Selection n Anything we ask a Measurable to do... n...will be part of the interface  because our compile-time checking made sure n The Measurable object knows how to do it  because of compile-time checking of class n Object uses its own version of the method  known as late (or dynamic) binding In C++, early (static) binding chooses a version of the method at compile time.

Variables & Types n Measurable variable is polymorphic  can hold a Circle or Rectangle object  can assign from a different type variable Measurable m; Circle c = new Circle(10); Rectangle r = new Rectangle(10, 20); m = c; m = r; Compare storing an int variable into a double variable: int n = 5; double x = n;

Variables & Types n Cannot go the other way around Measurable m = new Circle(10); Rectangle r; Circle c; r = m; c = m;  doesn’t like either of those Compare storing a double variable into an int variable: double x = 5.0; int n = x;

Crash Type Casting n Can tell Java you want to do it anyway!  tell Java to treat the Measurable as a Circle Measurable m = new Circle(10); Circle c; c = (Circle) m;  will crash if object is wrong type Rectangle r; r = (Rectangle) m; Contrast casting a double variable into an int variable: double x = 5.5; int n = (int)x;

Checking the Type n Can ask if an object is a given type  hey, m, are you are Circle? if (m instanceof Circle) { Circle c = (Circle) m; Circle c = (Circle) m; double radius = c.getRadius(); double radius = c.getRadius(); n Still can’t ask m to do non-Measurable stuff if (m instanceof Circle) System.out.print(m.getRadius()); System.out.print(m.getRadius()); Note: all lower-case letters!

Exercise n Check a Measurable variable to see if it holds a Rectangle object.  if it does, print out the Rectangle’s length and width

Implementing Multiple Interfaces n Can implement more than one interface  list interfaces, separated by commas public class MultiPurpose implements InterA, InterB {...} public class Yikes implements IA, IB, IC, IDa, IDb {...} n Must define every method from every interface it implements  no lying!

Extending Interfaces n Consider this interface: public interface Polygonal { public double getArea(); public double getArea(); public double getPerimeter(); public double getPerimeter(); public int getNumberOfSides(); public int getNumberOfSides();}  has all Measurable’s methods, plus one more n Can simplify the definition: public interface Polygonal extends Measurable { public int getNumberOfSides(); public int getNumberOfSides();} See Polygonal.java

Implementing Polygonal n Anything that implements Polygonal must define all the methods mentioned in Polygonal interface... public int getNumberOfSides() n...plus all those mentioned in Measurable public double getArea() public double getPerimeter()

And So On... n Can extend an interface that extends another  just adding more methods to implement public interface RegularPolygonal extends Polygonal {...} n Can extend more than one interface  again, adding more methods to implement public interface FiniteSurface extends Measurable, Colourable {......} Measurable Polygonal RegularPolygonal Colourable FiniteSurface See them!

Combining Interfaces n When one interface extends two others...  (or more than two others) n...it may not need any more methods  it just puts those two (or more) interfaces together  use empty braces (no new methods required) public interface FiniteSurface extends Measureable, Colourable {} extends Measureable, Colourable {}

Exercise n What methods must these classes implement? public interface IA {public void is();} public interface IB {public int howMany();} public interface IC extends IB {public String whatKind();} public interface ID extends IA, IC {} public interface IE extends IA, IB {public void what();} public class A implements IE {...} public class B implements ID {...} public class C implements IA, IB {...}

Interface Summary n An interface is a data type  variables can have that data type »including (especially) parameters for methods  such variables (methods) called polymorphic n An interface lists public methods  each implementing class implements them  each class has its own implementation  these classes are similar kinds of things »Circles and Rectangles are similar kinds of things

The Comparable Interface n Collections.sort sorts Lists of some types  Java must know how to sort them  knows how to sort Integer, Double, String, …  doesn’t know how to sort user-defined classes n Tell Java how to sort user-defined classes  implement the Comparable interface  Collections.sort expects to be given a List >

The Comparable Interface n Have to fill in the n Have to fill in the  what kind of thing it can be sorted with  almost always itself public class Student implements Comparable public class Student implements Comparable n Has exactly one method  compareTo says how to compare to other public int compareTo(Student other) »how does this Student compare to other Student »for Professor: public int compareTo(Professor other)

Sorting Students n Let’s sort Students by name  name is a String  String has a compareTo method  so just return whatever it returns public int compareTo(Student other) { return this.name.compareTo(other.name); return this.name.compareTo(other.name);}  “if you want to compare Students, compare their names.” See byName/Student.java

Sorting Students n Add Students to list; sort list; print list List ss = new ArrayList<>(); ss.add(new Student(“Jake”)); ss.add(new Student(“Angie”)); ss.add(new Student(“Geety”)); Collections.sort(ss);System.out.println(ss); [Angie (A ), Geety (A ), Jake (A )] See byName/SortStudents.java

Sorting by Grade n Sorting by numbers uses subtraction  smallest to largest: this.number – other.number  largest to smallest: other.number – this.number  but result must be an int! public int compareTo(Student other) { return other.getAverage() – this.getAverage(); return other.getAverage() – this.getAverage();}  sorts Students from highest to lowest grade See byGrade/Student.java and byGrade/SortStudents.java

Sorting by Double Values n Need to change double to int  (int) no good – changes 0.5 to 0 instead of 1 n Use Math.signum to get sign of result  then change to int public int compareTo(Line other) { double result = this.length – other.length; double result = this.length – other.length; double sign = Math.signum(result); // -1.0, 0.0, or +1.0 double sign = Math.signum(result); // -1.0, 0.0, or +1.0 return (int)sign; return (int)sign;} »sorts from shortest to longest See Line.java and SortLines.java

Exercise n Write a compareTo method that sorts Students by A_NUMBER  remember, it’s a String n Write a compareTo method that sorts Lines from longest to shortest  each Line has a length

Questions? n (Bonus material follows)  having multiple sorting methods for one class  the Comparator interface  anonymous classes

Sorting in Many Ways n Sometimes want to sort by name, other times by grade (and other times by A#)  Collections.sort accepts a second argument  it’s a “way to sort” »Collections.sort(words, String.CASE_INSENSITIVE_ORDER);  we’ll want (at least) these “ways to sort”: »Student.BY_NAME »Student.BY_GRADE »Student.BY_ANUMBER

The Comparator Interface n The interface for “ways to sort” n Need a class to implement the interface  so we need three classes public class SortStudentsByName implements Comparator { … } public class SortStudentsByGrade implements Comparator { … } public class SortStudentsByANumber implements Comparator { … } See the folder comparators/withClasses in this week’s sample code

The Comparator Interface n The interface for “ways to sort”  has exactly one method: int compare(_, _)  very similar to compareTo method public class SortStudentsByName implements Comparator { public int compare(Student one, Student other) { public int compare(Student one, Student other) { return one.getName().compareTo(other.getName()); return one.getName().compareTo(other.getName()); }}

Student Comparators n Each comparator in Student is a Comparator  each one is an object of the corresponding class public static final Comparator BY_NAME = new SortStudentsByName(); public static final Comparator BY_GRADE = new SortStudentsByGrade(); public static final Comparator BY_ANUMBER = new SortStudentsByANumber(); See comparators/withClasses/Student.java

All Those Extra Classes? n Don’t actually need to create new files  don’t need SortStudentsByName.java &c. n Use “anonymous” classes instead  put Comparator definition inside Student.java public static final Comparator BY_NAME = new Comparator () { public int compare(Student one, Student other) { public int compare(Student one, Student other) { return one.getName().compareTo(other.getName()); return one.getName().compareTo(other.getName()); } }; }; See the folder comparators/anonymous in this week’s sample code

Anonymous Classes n Class without a name  can use it to implement any interface  just need to give the definitions SomeInterface blah = new SomeInterface() { // define all interface methods in here! // define all interface methods in here!};  only makes sense for some interfaces »nothing that needs its own instance variables »Comparator makes sense; Comparable doesn’t

Questions n Next week: review on Tuesday n 2 nd midterm test on Thursday  on weeks 5, 6 and 7  usual rules apply