Title: 308203A Introduction to Computing II Lecture 3: Interfaces and Inheritance
1308-203AIntroduction to Computing IILecture 3
Interfaces and Inheritance
Fall Session 2000
2Interfaces
- More than one class may perform the same service
- e.g. Planes, trains and automobiles
- Interfaces describe what classes can do
3Example
interface Vehicle float costOfTrip(
) ...
4Example
class Car implements Vehicle float
costOfTrip( )
interface Vehicle float costOfTrip(
) ...
class Train implements Vehicle float
costOfTrip( )
5Example
Vehicle chooseLeastExpensive(Vehicle
choices) for (int j 0 j lt
choices.length j) if (choicesj.costOfTrip(
) lt best) bestVehicle choicesj best
choicesj.costOfTrip( )
6Whats the point
- We can manipulate objects without knowing
- their exact class
- Code we write will work, even with new
- kinds of objects
- Weve abstracted a kind of behavior
7Polymorphism
Definition Polymorphism is the ability of a
method call to invoke an underlying method
apropriate to the type of the object.
8Any questions?
9Interface shortcomings
- What if two classes share not only behavior
- but data? E.g. all vehicles have
wheels - What if two classes have methods which are
- implemented in the same way?
- What if we want to change the behavior of a
- class slightly?
10Inheritance
- Make new classes based on a previous class
- Behavior remains the same unless overriden
- Code can be modified incrementally, without
- restarting from scratch for each class
- Code can be shared
11Terminology
Superclass - a class on which another class is
based Subclass - a class derived from another
class Override - the replacement of a method
inherited from a superclass by
some new method
12Related Java Keywords
- extends - what class do we build on
- this - lets an object refer to itself
- super - lets an object refer to methods
- as defined in its superclass
- final - prevents a method from being overriden
- abstract - indicates that a method is undefined
and - must be overriden in the
subclass
13Public/private/protected
Keywords to restrict access to methods/data
- Public - visible by any other class
- Private - visible only by this class (not
subclasses!) - Protected - visible to this class and subclasses
14A Simple Example
public class Workaholic extends Worker
public doWork( ) super.doWork(
) drinkCoffee( ) super.doWork( )
15Any questions?