Presentation is loading. Please wait.

Presentation is loading. Please wait.

258 3/30/98 CSE 143 Object-Oriented Programming [Chapter 11]

Similar presentations


Presentation on theme: "258 3/30/98 CSE 143 Object-Oriented Programming [Chapter 11]"— Presentation transcript:

1 258 3/30/98 CSE 143 Object-Oriented Programming [Chapter 11]

2 259 3/30/98 OO Programming  What is Object-Oriented Programming (OOP)?  A buzzword used by marketing to make a product sound neater than it really is?  A good thing to be able to list on your résumé?  Another name for programming using ADTs?  A great way of organizing related ADTs, managing variations on a theme, avoiding code duplication, and supporting code reuse?

3 260 3/30/98 One Definition  OOP is:  Encapsulation (ADTs, classes), plus  Inheritance, plus  Dynamic dispatching (virtual functions)  Inheritance:  Related ADTs can be organized into hierarchies without code duplication and with easy extensions  Dynamic Dispatching (virtual functions)  Different but related classes can be mixed at run-time  Also called run-time polymorphism

4 261 3/30/98 Motivation for OOP  Often end up with several related ADTs when designing a project  “related” = shares common operations and properties in interface and/or implementation  Example: many collection ADTs share some basic member functions (isFull(), sizeOf(), isEmpty())  ADTs can be grouped into classification hierarchies:  by interface  by implementation

5 262 3/30/98 Classic Example Animal MammalFishReptile BovineCanineFeline “a kind of” Dog Tuna CowCat Shark CrocIguana abstract class concrete class instance FidoSocks “is an instance of”

6 263 3/30/98 Another Example Collections Ordered CollectionsUnordered Collections Array List Queue Stack Record Set DirectSequential Bag HeterogeneousHomogeneous Table aStack

7 264 3/30/98 Inheritance  Can organize classes into hierarchies in object- oriented languages (like C++)  More general class (higher up on classification hierarchy) is a base class or superclass  More specific class is a derived class or subclass  Usually, classes have at most one base class  "Single" inheritance  In some OO-languages (like C++), can have multiple base classes  Multiple inheritance  Controversial not in Java

8 265 3/30/98 Impact of Inheritance  Main effect:  All data and function members of a superclass are automatically inherited by derived classes  Like copying from superclass definition and code and pasting into derived class  Subclasses only contain differences from the base class  Subclasses are much smaller and simpler to write  Changes to a base class are automatically passed to derived classes, without having to change derived class!

9 266 3/30/98 Extension by Subclasses  Subclasses can:  Add new variables to those inherited from superclass  Add new operations to those inherited from superclass  Override (replace) inherited operations with customized versions more appropriate to subclass  Subclasses cannot:  Remove any instance variable or operation  Access any private data of the superclass

10 267 3/30/98 Example: A Point class  Say we want to store colored points. We have already: class Point { public: Point(int initX, int initY); int X(); int Y(); void Print(); private: int x, y; };  How to use inheritance to handle ColoredPoints ?

11 268 3/30/98 A ColoredPoint Class class ColoredPoint { public: ColoredPoint(int x, int y, Color c); int X(); int Y(); void Print(); Color getColor(); private: int x, y; Color color; };  But this isn’t using inheritance. How to change?

12 269 3/30/98 Again, with Inheritance class ColoredPoint : public Point { public: ColoredPoint(int x, int y, Color c); // X() and Y() functions are now inherited void Print(); // overrides Point’s Print() // Also want to get the color Color getColor(); private: // x and y variables are inherited Color color; };

13 270 3/30/98 Implementation ColoredPoint::ColoredPoint(int x, int y, Color c) : Point(x,y) { color = c; } Color ColoredPoint::getColor() { return color; } void ColoredPoint::print() { cout << “(“ << X() << “,” << Y() << “)”; cout << color << endl; }

14 271 3/30/98 To Build a Subclass:  Add : public BaseClassName to the first line of class declaration  Add : BaseClassName(arguments) to beginning of constructor’s definition  Only needed to invoke non-default constructor  Default constructor of base class is otherwise invoked automatically  Don’t rewrite inherited methods, instead inherit them  Can’t change or re-declare inherited data member

15 272 3/30/98 When to Use Inheritance?  Most appropriate if all of the following are true:  Interface of derived class is superset of base class interface (all functions from base and then some)  Representation of derived class is superset of base class representation (all data from base and then some)  Subclass implementation is similar to implementation of base class  The subclass A "is a kind of” the base class B  If the relationship is "A has a B", then B is typically a member variable of A, not a base class of A.

16 273 3/30/98 When Not to Use Inheritance?  Don’t use inheritance when:  Derived class has the base class as a part A bird has a wing, but is not a kind of wing  Derived class doesn’t have same representation and/or interface as base class Can often reorganize class hierarchy to fix the problem Use different class as base class Make small changes to other classes

17 274 3/30/98 Inheritance and Scoping  Already seen two types of class members:  public : Visible to everyone  private : Only visible to class itself  With subclassing, there is a third option  protected : Visible to class and its subclasses, but not to clients outside the class

18 275 3/30/98 Example class Point { public: Point(int x, int y); int X(); int Y(); void Print(); protected: int x, y; // For subclasses of Point only }; class ColoredPoint : public Point { public: ColoredPoint(int x, int y, Color c); void Print(); // overrides Point’s Print() PointColor Color(); protected: Color color; };

19 276 3/30/98 Invoking Overridden Functions  Sometimes, may override a function in a subclass, but want to be able to call same function in base class  Often used to simplify work Subclass function can call same function from base class to do some work, and do specialized part itself  Don’t want to have to copy code from base class  Use an explicitly qualified call  ClassName::function(arguments) instead of just function(arguments)

20 277 3/30/98 Example class Point { public: void Draw(); // Rest the same }; class ColoredPoint : public Point { void Draw(); // Override to draw in color … }; void Point::Draw() { … } void ColoredPoint::Draw() { // Set current color to point’s color SetPenColor(Color()); // Use Point’s Draw() function to do work Point::Draw(); };

21 278 3/30/98 Inheritance and Constructors  Constructors are not inherited!  Can’t be, because their name specifies which class they’re part of!  Instead, constructor of base class is called automatically before the subclass constructor is  Can call base class constructor explicitly to pass parameters (like in ColoredPoint example)  If omitted, default constructor of base class is called

22 279 3/30/98 Inheritance and Destructors  Like constructors, destructors are not inherited either  Like constructors, base class destructor is called automatically  Base class destructor runs after subclass destructor  Reverse order of constructor calls  Ordering for constructors is: base to derived  Ordering for destructors is: derived to base

23 280 3/30/98 Dynamic Dispatching  A public subclass can be used wherever a superclass is expected  Subclass has (at least) all operations and data of the superclass  Client code expecting a superclass can still do what it wants  Can take code written for a superclass and reuse it for any subclass, without any changes!  Cannot go the other way  Base class will probably not have same operations and data as a derived class  Derived classes add to (augment) a base class

24 281 3/30/98 Example class Point { … } ; class ColoredPoint : public Point { … } ; void DrawPoint(Point p) { DrawPixelAt(p.X(), p.Y()); };... DrawPoint(Point(3, 4)); // Just what’s expected DrawPoint(ColoredPoint(3, 4, RED)); // Also legal!

25 282 3/30/98 One Problem  Function overriding doesn’t work so well for this sort of reuse: class Point { void Print(); }; class ColoredPoint : public Point { void Print(); // Overrides Point’s Print() }; void PrintAPoint(Point *pt) { pt->Print(); } Point *p = new Point(3, 4); ColoredPoint *cp = new ColoredPoint(5,6,RED); PrintAPoint(p); // “(3, 4)” PrintAPoint(cp); // “(5, 6)” oops!!!!

26 283 3/30/98 C++ Rule  When calling a member function on a pointer or reference, use the static (compile-time) type to decide which overloaded version to call  Ignore any overriding versions for the dynamic (run- time) type actually being pointed to  Static type of pt : Point *  Dynamic type of pt : Point * or ColoredPoint *  Without using pointers, it’s not a problem  Static and dynamic types are the same

27 284 3/30/98 Fixing the Default Behavior  There is a way to have C++ determine which overloaded function is the “right” one to call at run-time  I.E., Make C++ use dynamic type, not static type  Declaration of the initial (most general) version of member function must start with the virtual keyword  Overriding versions in subclasses may or may not have the virtual keyword Still virtual without keyword, so use it for better style  Rule of thumb: If you may ever want to override a function, make it virtual !

28 285 3/30/98 Example class Point { virtual void Print(); }; class ColoredPoint : public Point { virtual void Print(); // Overrides Point’s print }; void PrintAPoint(Point *pt) { pt->Print(); } Point *p = new Point(3, 4); ColoredPoint *cp = new ColoredPoint(5,6,RED); PrintAPoint(p); // “(3, 4)” PrintAPoint(cp); // “(5, 6), Red” like we want! Optional, but better for style reasons

29 286 3/30/98 Another Example  Remember, virtual functions only work with pointers: class Point { virtual void Print(); }; class ColoredPoint : public Point { virtual void Print(); // Overrides Point’s Print() }; void PrintAPoint(Point pt) { pt.Print(); } Point *p = new Point(3, 4); PrintAPoint(p); // “(3, 4)” ColoredPoint *cp = new ColoredPoint(5, 6, RED); PrintAPoint(cp); // “(5, 6)” NOT “(5, 6), Red” An actual instance instead of a pointer

30 287 3/30/98 Handling Function Calls  For calling a member function, the compiler does the following:  For a non-virtual member function, the static type of the invoking object is determined Makes a normal procedure call to the right one  For a virtual member function, it produces code which will determine the dynamic type of the object at run- time and look in a table to see which function to call  Slower than a normal call, but does the right thing Called dynamic dispatching  How much slower is a call to a virtual function?

31 288 3/30/98 Without Pointers or Refs  Function is determined statically (at compile time) BaseClass B (... ); SubClass S (... ); B.talk( ); //base class version S.talk( );//sub class version B = S; //legal (a "slice"), but... B.talk ( );//still the base class version S = B;//not legal

32 289 3/30/98 With Pointers or Refs  Function is still determined statically unless it's a base class pointer and a virtual function BaseClass * Bp = new BaseClass (... ); SubClass * Sp = new SubClass (... ); Bp->talk( ); //base class version Sp->talk( ); //sub class version Bp = Sp; //legal (not a "slice") Bp->talk ( );//still the base class version if talk is non-virtual, sub class version if talk is virtual Sp = Bp;//not legal

33 290 3/30/98 Abstract vs. Concrete Classes  Some classes may be more ideas than actual usable objects  All shapes can be drawn, but there’s no “default” way of drawing one  Known as an abstract class  Classes intended to be used directly are called concrete classes  A circle knows how to draw itself  Shouldn’t create instances of an abstract class, only concrete classes

34 291 3/30/98 Abstract Classes  Many abstract classes may not be able to be fully implemented  Member functions will be implemented only inside concrete subclasses  May not be a reasonable default implementation of the function Drawing an abstract shape instead of a concrete square or circle  May want to leave placeholders in abstract class to ensure that subclasses have those functions All shapes can be drawn, but not an “abstract shape”

35 292 3/30/98 Pure Virtual Functions  We can add placeholders to an abstract class to make sure that all derived classes implement the functions we want: class Shape { public: virtual Draw() = 0; };  Draw() is a pure virtual function  Shape::Draw() cannot be implemented  All subclasses must declare and implement a Draw() function of their own

36 293 3/30/98 Pure Virtual Functions (2)  Pure virtual functions can be:  Overridden with a real function  Must be overridden in all concrete subclasses  Called, even from functions in the abstract class

37 294 3/30/98 Beyond Objects: Components  Component: a "sealed" object  Some methods and data are "exposed" to the outside world  Language-neutral  source code not visible  may be used within any compliant programming language or environment, maybe even at a distance.  Supporting and related technologies  Microsoft: VB, COM, OLE, Active-X, ASP, etc.  Sun: JavaBeans  CORBA  Scripting languages (VBScript, JavaScript, etc.)

38 295 3/30/98 Trends in Programming Old School  Input/process/output  Vendors provide libraries of functions  Programmer calls functions  COBOL, C/C++, Ada, Pascal, etc.  Data stored in files and databases New Wave  Event-driven  Vendors provide libraries of classes and components  Programmer inherits from classes, links components together  C++, Java, Visual Basic, scripting languages, etc.  All that, plus data from OO databases, persistent object stores, networks

39 296 3/30/98 Summary  Object-Oriented Programming  Inheritance  Use for a kind of, not has a relations  Classification Hierarchies  Superclass (base class), subclass (derived class)  Overriding functions  Dynamic Dispatching  Virtual functions  Pure virtual functions


Download ppt "258 3/30/98 CSE 143 Object-Oriented Programming [Chapter 11]"

Similar presentations


Ads by Google