1 / 39

CSE 143

CSE 143. Object-Oriented Programming [Chapter 11]. 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?

jcallie
Télécharger la présentation

CSE 143

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSE 143 Object-Oriented Programming [Chapter 11]

  2. 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. 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. 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. Classic Example abstract class concrete class instance Animal “a kind of” Mammal Fish Reptile Bovine Canine Feline Tuna Shark Iguana Croc Cow Dog Cat “is an instance of” Fido Socks

  6. Another Example Collections Ordered Collections Unordered Collections Direct Sequential Heterogeneous Homogeneous Array Record List Stack Table Set Queue Bag aStack

  7. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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 Trends in Programming

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

More Related