A Introduction to Computing II Lecture 3: Interfaces and Inheritance Fall Session 2000
Interfaces More than one class may perform the same service e.g. Planes, trains and automobiles Interfaces describe what classes can do
Example interface Vehicle { float costOfTrip( );... }
Example interface Vehicle { float costOfTrip( );... } class Car implements Vehicle { float costOfTrip( ) { … } } class Train implements Vehicle { float costOfTrip( ) { … } }
Example Vehicle chooseLeastExpensive(Vehicle[] choices) { … for (int j = 0; j < choices.length; j++) if (choices[j].costOfTrip( ) < best) { bestVehicle = choices[j]; best = choices[j].costOfTrip( ); } … }
What’s the point We can manipulate objects without knowing their exact class Code we write will work, even with new kinds of objects We’ve abstracted a kind of behavior
Polymorphism Definition: Polymorphism is the ability of a method call to invoke an underlying method apropriate to the type of the object.
Any questions?
Interface 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?
Inheritance 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
Terminology 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
Related 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
Public/private/protected Public - visible by any other class Private - visible only by this class (not subclasses!) Protected - visible to this class and subclasses Keywords to restrict access to methods/data
A Simple Example public class Workaholic extends Worker { public doWork( ) { super.doWork( ); drinkCoffee( ); super.doWork( ); }
Any questions?