Interfaces and Inheritance PowerPoint PPT Presentation

presentation player overlay
About This Presentation
Transcript and Presenter's Notes

Title: Interfaces and Inheritance


1
Interfaces and Inheritance
  • Alyce Brady

2
Motivation Working with
  • Generic and Abstract Algorithms
  • Generic and Abstract Data Structures
  • Related Classes

3
One Solution Untyped Variables
  • sort array of untyped objects (might be students,
    fish, or balloons)
  • for (j0 j lt array.length-1 j)
  • int minInd j
  • for (kj1 k lt array.length k)
  • if (arrayk lt arrayminInd)
  • minInd k
  • swap(array, j, minInd)

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 lt operator isnt defined for item being
    sorted?
  • What if different algorithm implementations use
    different operation names?

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

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.

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.

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

10
Interfaces An Example
  • Student (or balloon or fish)
  • public class Student
  • implements Comparable
  • public int compareTo(Object other)
  • ltcode that compares 2 studentsgt

11
Interfaces An Example
  • sort array of Comparable
  • Comparable array
  • for (j0 j lt array.length-1 j)
  • int minInd j
  • for (kj1 k lt array.length k)
  • Comparable c1 arrayk
  • Comparable c2 arrayminInd
  • if (c.compareTo(c2) lt 0)
  • minInd k
  • swap(array, j, minInd)

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

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.

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.

15
Interfaces Another Example
  • Stack
  • public interface Stack
  • void push(Object element)
  • Object pop()
  • Object peekTop()

16
Interfaces Another Example
  • A Stack implementation
  • public class ArrayStack
  • implements Stack
  • public void push(Object element)
  • ltcode puts element on stackgt

17
Interfaces Another Example
  • Use Stack Interface
  • Stack s new ArrayStack()
  • // or new LinkListStack()
  • ElemType anElement new ElemType()
  • s.push(anElement)
  • ElemType e1 (ElemType)s.peekTop()
  • ElemType e2 (ElemType)s.pop()
  • Variable s can refer to any Stack implementation
    object.

18
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 objects
    class, at run-time. (dynamic binding)

19
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

20
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

21
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

22
Interfaces Dont 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

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

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

25
Inheritance An Example
  • SlowFish
  • public class SlowFish extends Fish
  • // dont declare inherited stuff
  • // additional instance variable
  • double probOfMoving
  • // redefine nextLocation method
  • protected Location nextLocation()
  • ltnew implementationgt

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

27
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).

28
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 lt list.length k)
  • Object obj list.get(k)
  • System.out.println(obj.toString())
  • Can only use Object methods with obj.

29
Casting
  • ArrayList
  • ArrayList list new ArrayList()
  • list.add(new Fish())
  • list.add(new DarterFish())
  • for (int k 0 k lt 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.

30
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.)

31
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

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

33
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).
Write a Comment
User Comments (0)
About PowerShow.com