Presentation is loading. Please wait.

Presentation is loading. Please wait.

Interfaces and Inheritance

Similar presentations


Presentation on theme: "Interfaces and Inheritance"— Presentation transcript:

1 Interfaces and Inheritance
Alyce Brady 9/19/2018

2 Motivation: Working with…
Generic and Abstract Algorithms Generic and Abstract Data Structures Related Classes Generic Algorithms: e.g., sorting algorithms to sort students, or balloons, or fish, or …. Sorting algorithm is the same even though the element types are different. Abstract Algorithms: client code might just call a sort function, for which there are many implementations (or strategies). Generic Data Structures: e.g., classes for lists of students, lists of balloons, etc. Operations on the list are the same even though the element types are different. Abstract Data Structures: e.g., collection classes implemented in various ways Related Classes: e.g., why repeat data fields (and the operations on them) like name, address, phone number in many, related classes (such as students, teachers, staff)? 9/19/2018

3 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); an ideal solution for writing generic ALGORITHMS 9/19/2018

4 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? 9/19/2018

5 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). 9/19/2018

6 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. Only care about object size when constructing new object. (Constructor needs this info, not client code.) Only care about layout when accessing instance and class variables. (If instance variables are private, this is from within class methods.) Compilers do need to know the set of operations that are available (and visible) when compiling client code. 9/19/2018

7 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. 9/19/2018

8 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. 9/19/2018

9 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) 9/19/2018

10 Interfaces: An Example
Student (or balloon or fish): public class Student implements Comparable { public int compareTo(Object other) <code that compares 2 students> } 9/19/2018

11 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); an ideal solution for writing generic ALGORITHMS 9/19/2018

12 Interfaces: Second Example
Locatable: public interface Locatable { Location location(); } an object that keeps track of, and can report, its location is a Locatable object 9/19/2018

13 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. 9/19/2018

14 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. 9/19/2018

15 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) Dynamic: indicates run-time Static: indicates compile-time Dynamic binding: binding of method call (message being passed) to actual code being executed (method) is made at run-time, rather than at compile time. Some books use “polymorphism,” but method and operator overloading are other types of polymorphism. 9/19/2018

16 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 9/19/2018

17 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 9/19/2018

18 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 9/19/2018

19 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 9/19/2018

20 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. 9/19/2018

21 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. 9/19/2018

22 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> } 9/19/2018

23 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. An inherited method may NOT call a redefined method if the redefined method is private. In that case the inherited method will invoke the method from the superclass being overridden, since it has access to that version of the method. A redefined method may NOT call an inherited method if the inherited method is private. This will generate a compile-time error. 9/19/2018

24 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). 9/19/2018

25 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. 9/19/2018

26 Casting ArrayList: Can use any Fish methods with f.
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. 9/19/2018

27 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.) 9/19/2018

28 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 9/19/2018

29 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. Dynamic: indicates run-time Static: indicates compile-time Dynamic binding: binding of method call (message being passed) to actual code being executed (method) is made at run-time, rather than at compile time. Some books use “polymorphism,” but method and operator overloading are other types of polymorphism. 9/19/2018

30 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). 9/19/2018


Download ppt "Interfaces and Inheritance"

Similar presentations


Ads by Google