300 likes | 426 Views
Interfaces and Inheritance. Alyce Brady. Motivation: Working with…. Generic and Abstract Algorithms Generic and Abstract Data Structures Related Classes. One Solution: Untyped Variables. sort array of untyped objects (might be students, fish, or balloons)
E N D
Interfaces and Inheritance Alyce Brady
Motivation: Working with… • Generic and Abstract Algorithms • Generic and Abstract Data Structures • Related Classes
One Solution: Untyped Variables • sort array of untyped objects (might be students, fish, or balloons) for (j=0; j < array.length-1; j++) { int minInd = j; for (k=j+1; k < array.length; k++) { if (array[k] < array[minInd]) minInd = k; } swap(array, j, minInd); }
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?
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).
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.
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.
Interfaces: An Example • Comparable: interface specifies the compareTo 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 compareTo method for the particular object.
Interfaces: An Example • Comparable: public interface Comparable { int compareTo(Object other); } • compareTo returns negative number (this object is less than other), 0 (equal to), or positive number (greater than)
Interfaces: An Example • Student (or balloon or fish): public class Student implements Comparable { … public int compareTo(Object other) { <code that compares 2 students> } … }
Interfaces: An Example • sort array of Comparable Comparable array[…]; for (j=0; j < array.length-1; j++) { int minInd = j; for (k=j+1; k < array.length; k++) { Comparable c1 = array[k]; Comparable c2 = array[minInd]; if (c.compareTo(c2) < 0) minInd = k; } swap(array, j, minInd); }
Interfaces: Second Example • Locatable: public interface Locatable { Location location(); } • an object that keeps track of, and can report, its location is a Locatable object
Interfaces: Third Example • Environment: interface that specifies methods like numObjects, allObjects, objectAt, etc. • There can be many ways to represent an environment. Classes that implement the Environment interface must implement that set of methods.
Interfaces: Third Example • Client code written in terms of interface everywhere except object construction. Environment env = new BoundedEnv(); // or new UnboundedEnv(); Locatable[] theObjects = env.allObjects(); • Methods are dynamically bound to right class. • Side note: All objects in an Environment must be Locatable.
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)
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
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
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
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
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.
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.
Inheritance: An Example • SlowFish: public class SlowFish extends Fish { // don’t declare inherited stuff // additional instance variable double probOfMoving; // redefine nextLocation method protected Location nextLocation() { … <new implementation> } }
Inheritance: An Example • SlowFish inherits some methods (e.g., move, changeLocation) and redefines some methods (e.g., nextLocation). • Inherited method may call redefined method (e.g.,move calls nextLocation). Cannot be private. • Redefined method may call inherited method (e.g.,nextLocation calls changeLocation). Cannot be private.
Inheritance: Another Example • All classes extend the Object class (or a subclass of Object). • All classes inherit or redefine the equals and toString methods from Object. • Any object may be put in an ArrayList (or other collection class) because they expect objects of type Object(and all objects are of type Object).
Inheritance: Another Example • ArrayList: ArrayList list = new ArrayList(); list.add(new Fish()); list.add(new DarterFish()); list.add(new Balloon()); for (int k = 0; k < list.length; k++) { Object obj = list.get(k); System.out.println(obj.toString()); } • Can only use Object methods with obj.
Casting • ArrayList: ArrayList list = new ArrayList(); list.add(new Fish()); list.add(new DarterFish()); for (int k = 0; k < list.length; k++) { Fish f = (Fish) list.get(k); f.act(); } • Can use any Fish methods with f. • First, have to cast Object returned by list.get to Fish.
Casting • Compiler knows only that things in the ArrayList 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.)
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
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.
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., DarterFish IS-A Fish; Balloon is NOT a Fish).