Interfaces and Inheritance Alyce Brady 12262021 1 Motivation
Interfaces and Inheritance Alyce Brady 12/26/2021 1
Motivation: Working with… ® Generic and Abstract Algorithms ® Generic and Abstract Data Structures ® Related Classes 12/26/2021 2
One Solution: Untyped Variables ® sort array of untyped objects (might be students, fish, or balloons) for (j=0; j < array. length-1; j++) { int min. Ind = j; for (k=j+1; k < array. length; k++) { if (array[k] < array[min. Ind]) min. Ind = k; } swap(array, j, min. Ind); } 12/26/2021 3
Issues ® Types enable compilers to do low-level semantic (not just syntactic) checking. ® Memory logistics: How can a variable hold items of different types? ® Operation overloading: How does system know which operation to execute? ® What if < operator isn’t defined for item being sorted? ® What if different algorithm implementations use different operation names? 12/26/2021 4
Big Issue: What IS a Type? ® Used to be something that defines: ® size of object ® layout of internal representation ® set of operations ® Compilers needed to know all three to compile client code (code with variables of the type). 12/26/2021 5
Big Issue: What IS a Type? ® Since Java variables are references, what do compilers need to know (and when)? ® size: only when compiling class constructors ® layout: mostly when compiling class methods ® operations: when compiling code with variables of the type ® So for client code, a type is a set of operations. 12/26/2021 6
Using Interfaces ® Define a set of methods as an interface. ® Create classes that implement those methods. ® Use interface as variable type; variable can refer to an object of any class that implements the interface. ® Compiler can verify that method calls are valid; classes that implement the interface support all the methods of the interface. 12/26/2021 7
Interfaces: An Example interface specifies the compare. To method (indicates the object is less than, equal to, or greater than another object). ® Sorting algorithms (and min/max, etc) can work on objects of any classes that implement Comparable. ® Run-time environment will call the compare. To method for the particular object. ® Comparable: 12/26/2021 8
Interfaces: An Example ® Comparable: public interface Comparable { int compare. To(Object other); } returns negative number (this object is less than other), 0 (equal to), or positive number (greater than) ® compare. To 12/26/2021 9
Interfaces: An Example ® Student (or balloon or fish): public class Student implements Comparable { … public int compare. To(Object other) { <code that compares 2 students> } … } 12/26/2021 10
Interfaces: An Example ® sort array of Comparable array[…]; for (j=0; j < array. length-1; j++) { int min. Ind = j; for (k=j+1; k < array. length; k++) { Comparable c 1 = array[k]; Comparable c 2 = array[min. Ind]; if (c. compare. To(c 2) < 0) min. Ind = k; } swap(array, j, min. Ind); } 12/26/2021 11
Interfaces: Second Example ® Locatable: public interface Locatable { Location location(); } ® an object that keeps track of, and can report, its location is a Locatable object 12/26/2021 12
Interfaces: Third Example interface that specifies methods like num. Objects, all. Objects, object. At, etc. ® Environment: ® There can be many ways to represent an environment. Classes that implement the Environment interface must implement that set of methods. 12/26/2021 13
Interfaces: Third Example ® Client code written in terms of interface everywhere except object construction. Environment env = new Bounded. Env(); // or new Unbounded. Env(); Locatable[] the. Objects = env. all. Objects(); ® Methods are dynamically bound to right class. ® Side note: All objects in an Environment must be Locatable. 12/26/2021 14
Interfaces: Key Ideas ® Interfaces define types (sets of methods). ® A variable of type T must refer to an object that supports methods defined by T, not necessarily to an instance of T. ® Actual method invoked is defined by the object’s class, at run-time. (dynamic binding) 12/26/2021 18
Interfaces: Support Generic and Abstract Algorithms üWriting a sort algorithm to sort students, balloons, fish ® algorithm operates on items whose type is an interface üWriting multiple implementations of a sort operation ® Various sort strategy classes can implement a single sort interface 12/26/2021 19
Do They Support Generic and Abstract Data Structures? ûCreating lists of students, balloons, fish ® Only if we write a new class (interface implementation) for each element type üSpecifying abstract data structures, like Environment ® Client code written to use abstract data structure will work with any implementation class 12/26/2021 20
Do They Support Related Data Structures? ûCommon data and operation implementations for students, teachers, staff? ® Interfaces have nothing to do with sharing data or method implementations 12/26/2021 21
Interfaces Don’t Solve … ® Generic Data Structures ® items (and their sizes) are different; operations for storing and retrieving are the same ® Related Classes ® some behavior (and data) is different; lots of behavior (and data) is the same 12/26/2021 22
Using Inheritance ® Create a new class by extending an existing class. ® The new class (subclass) inherits the data and methods of the existing class (superclass). (code reuse) ® Subclass can have additional data and methods. ® Subclass can redefine (override) inherited methods for different behavior. 12/26/2021 23
Using Inheritance ® Can use superclass as variable type; variable can refer to an object of the superclass or any subclass (since they inherit or redefine all methods of superclass). ® Method calls will be dynamically bound to redefined (or inherited) method implementations at run-time. 12/26/2021 24
Inheritance: An Example ® Slow. Fish: public class Slow. Fish extends Fish { // don’t declare inherited stuff // additional instance variable double prob. Of. Moving; // redefine next. Location method protected Location next. Location() { … <new implementation> } } 12/26/2021 25
Inheritance: An Example inherits some methods (e. g. , move, change. Location) and redefines some methods (e. g. , next. Location). ® Slow. Fish ® Inherited method may call redefined method (e. g. , move calls next. Location). Cannot be private. ® Redefined method may call inherited method (e. g. , next. Location calls change. Location). Cannot be private. 12/26/2021 26
Inheritance: Another Example ® All classes extend the Object class (or a subclass of Object). ® All classes inherit or redefine the equals and to. String methods from Object. ® Any object may be put in an Array. List (or other collection class) because they expect objects of type Object(and all objects are of type Object). 12/26/2021 27
Inheritance: Another Example ® Array. List: Array. List list = new Array. List(); list. add(new Fish()); list. add(new Darter. Fish()); list. add(new Balloon()); for (int k = 0; k < list. length; k++) { Object obj = list. get(k); System. out. println(obj. to. String()); } ® Can obj. 12/26/2021 only use Object methods with 28
Casting ® Array. List: Array. List list = new Array. List(); list. add(new Fish()); list. add(new Darter. Fish()); for (int k = 0; k < list. length; k++) { Fish f = (Fish) list. get(k); f. act(); } ® Can use any ® First, have to Fish methods with f. cast Object returned by list. get to Fish. 12/26/2021 29
Casting ® Compiler knows only that things in the Array. List are of type Object. ® Programmer knows that in this case they are all Fish. (Instances of Fish or of subclasses of Fish. ) ® Cast informs compiler of this. Compiler has no way to verify this claim. ® At run-time, system will verify that all objects returned by list. get are of type Fish. (Will throw exception if not. ) 12/26/2021 30
Inheritance Supports … üGeneric Data Structures ® collection classes act on any items of type Object; must cast to actual type üRelated Classes ® shared data and behavior are inherited from shared superclass; some behavior may be redefined in subclass; additional behavior may be added 12/26/2021 31
Interfaces & Inheritance: Key Ideas ® Interfaces and classes define types (sets of methods). ® A variable of type T must refer to an object of a class that implements T (if T is an interface), to an instance of T, or to an instance of a subclass of T. ® Dynamic binding means a method call is bound to the piece of code that will be executed at run-time. The executed method will be the one appropriate for the object on which it is invoked. 12/26/2021 32
Interfaces & Inheritance: Key Ideas Continued ® Interfaces provide a way to group classes that support certain methods. This creates type flexibility and type-safe dynamic binding, enabling programmers to write more generic algorithms. ® Inheritance provides a mechanism for code reuse as well as type flexibility and type-safe dynamic binding. Since subclasses are subtypes, subclasses should model the IS-A relationship (e. g. , Darter. Fish IS-A Fish; Balloon is NOT a Fish). 12/26/2021 33
- Slides: 30