Presentation is loading. Please wait.

Presentation is loading. Please wait.

308-203A Introduction to Computing II Lecture 3: Interfaces and Inheritance Fall Session 2000.

Similar presentations


Presentation on theme: "308-203A Introduction to Computing II Lecture 3: Interfaces and Inheritance Fall Session 2000."— Presentation transcript:

1 308-203A Introduction to Computing II Lecture 3: Interfaces and Inheritance Fall Session 2000

2 Interfaces More than one class may perform the same service e.g. Planes, trains and automobiles Interfaces describe what classes can do

3 Example interface Vehicle { float costOfTrip( );... }

4 Example interface Vehicle { float costOfTrip( );... } class Car implements Vehicle { float costOfTrip( ) { … } } class Train implements Vehicle { float costOfTrip( ) { … } }

5 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( ); } … }

6 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

7 Polymorphism Definition: Polymorphism is the ability of a method call to invoke an underlying method apropriate to the type of the object.

8 Any questions?

9 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?

10 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

11 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

12 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

13 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

14 A Simple Example public class Workaholic extends Worker { public doWork( ) { super.doWork( ); drinkCoffee( ); super.doWork( ); }

15 Any questions?


Download ppt "308-203A Introduction to Computing II Lecture 3: Interfaces and Inheritance Fall Session 2000."

Similar presentations


Ads by Google