CSE 143 "Class Relationships" • ... is the title of Chapter 8 • Let’s step back first to why we care Class Relationships and • Computer programs make a model of the world in order to solve some problem Inheritance • In the world, there are objects, and there often are relationships between them [Chapter 8, pp.343-354] 07/17/01 07/17/01 Q-1 Q-2 One Kind of Relationship Has-a vs. Is-a • At the bank: • A pencil has an eraser • Savings accounts and checking accounts are two kinds • But an eraser is not a kind of pencil or vice-versa of accounts • A pencil is a kind of writing tool • Commercial customers and regular customers are two • But a pencil doesn’t contain a writing tool or vice-versa types of customers • lions/tigers/teeth/mammals • Tellers, loan officers, and branch managers are kinds of • What relationships? employees • Customers and employees are kinds of people • "Kind of" relationships are everywhere • and therefore very important in modeling the real world in a computer 07/17/01 07/17/01 Q-3 Q-4 Class in a class: "has-a" Hierarchies of Organization • Use an instance of one class as a member • Often, we classify things in a hierarchy from variable in another general to specific class StudentCouncil { Student president; Collections Animal Student minister_of_propaganda; Ordered Collections Unordered Collections Student members_at_large[5]; Mammal Fish Reptile }; Direct Sequential Heterogeneous Homogeneous Canine Feline Tuna Shark Array Record • A "has-a" relationship List Stack Table Iguana Croc Set Wolf Dog Cat Queue Bag • A StudentCouncil "has-a" Student • Hierarchies show "is-a-kind-of" relationships In fact, more than one • A Dog "is-a-kind-of" Canine, a Shark "is-a-kind-of" • We've used this plenty already (e.g., strings, …) Animal • For "is-a", we'll need a different C++ feature • A Stack "is-a-kind-of" OrderedCollection 07/17/01 07/17/01 Q-5 Q-6 CSE 143 Q
Caution: Not Every Relationship is "is-a" or Is-a instance vs Is-a kind of "has-a" • dog/dog-owner • Commercial Customer is a kind of Customer mammal • Both are types • Instances of types are by now a very familiar person programming concept • One type being a kind of another type is a new concept dog dog-owner • Compare "Fluffy is a cat" vs. "Cats are owner walks dog carnivores." owner feeds dog dog bites owner 07/17/01 07/17/01 Q-7 Q-8 Modeling a Bank Why Focus on "is-a" and "has-a"? • A way to take advantage of redundancy • Bank has name • If Appointment contains (“has-a”) Date, and Date • Has branches is already defined, we don't have to start from • Branches have customers scratch • Customers have accounts • C++: use one type inside another • Multiple kinds of accounts (savings, checking, • Have seen lots of examples already etc). • "Is-a kind of" would be another way to take • Multiple kinds of people (employees vs advantage of redundancy customers) • If I had Mammal defined, a lot of that would carry over to • Multiple kinds of employees (tellers, loan officers, VPs, Lion. etc.) • For "is-a", we need some new C++ stuff: inheritance 07/17/01 07/17/01 Q-9 Q-10 Object - Bank Account Kinds of Bank Accounts C h e c kin g S a v in g s B ro k e ra g e • Accounts have certain data and operations M o n th ly fe e s In te re s t ra te Lis t o f s to c ks • Regardless of whether checking, savings, etc. M in im u m b a l. a n d b o n d s • Data • account number Each type shares some data and operations of • balance "account", and has some data and operations • owner of its own. • Operations Account • open • close • get balance Checking Savings Brokerage • deposit • withdraw 07/17/01 07/17/01 Q-11 Q-12 CSE 143 Q
Inheritance in C++ A Big Idea class Account { • Inheritance is a BIG IDEA class SavingsAccount : public ... Account { • One of the great new features of C++ double balance; ... • A key concept in modern programming Customer owner; • Essential for using today’s languages, tools, and Date dataOpened; libraries ... ... double interestRate; • However... void makeDeposit (double ... Amount); • The details in C++ can get messy ... ... void creditInterest( ); • Sometimes very, very, very, very messy. }; }; 07/17/01 07/17/01 Q-13 Q-14 Inheritance Terminology Toward Object-Oriented Programming • Inheritance is a major aspect of what is called • Inheritance is a way to encode the "is-a-kind-of" "object-oriented programming". relation in OO languages • Another is encapsulation , which we’re already • Shark declares that it "is-a-kind-of" Fish by inheriting using. from Fish • Data and methods packaged together in classes • A derived class inherits from a base class by • Public/private access control putting : public BaseClassName in the class • A third is polymorphism declaration • Constructor overloading is one example base class derived class • Operator overloading is another example (or superclass) (or subc lass) • We’ll also see virtual functions class Shark : public Fish { • Finally, OO is a matter of world-view rather than // Shark-specific stuff here just programming techniques } ; 07/17/01 07/17/01 Q-15 Q-16 Example: A Point Class Picturing the Hierarchy • We’re building a graphics system... class Point { base class Fish • Let’s say we had the public: (or superclass) Point( double x, double y ); following class "point" double getX(); double getY(); void print( ostream& os ); Shark • We can use inheritance private: double xpos; derived class to create a class of double ypos; (or subc lass) colored points based on }; this class All data and methods in base class (superclass) are automatically inherited by derived (sub) class 07/17/01 07/17/01 Q-17 Q-18 CSE 143 Q
ColorPoint Via Inheritance Point Hierarchy class ColorPoint : public Point { Point public: ColorPoint( double x, double y, • ColorPoint "is-a" Point base class Color c ); xpos ypos • Therefore ColorPoint has to (or superclass) // getX() is inherited from Point be able to do anything Point getx(), gety() // getY() is inherited from Point can print ( ) // New accessor method for the • All fields and methods of Point // Color field Color getColor(); are "inherited" by ColorPoint - they are transparently // We still need to redefine ColorPoint included! // the print method! void print( ostream& os ); • Derived class can add new derived class methods, fields private: color // xpos is inherited from Point (or subc lass) • Derived class can override // ypos is inherited from Point getcolor ( ) Color color; base class behavior (methods) }; print ( ) 07/17/01 07/17/01 Q-19 Q-20 Rules of Inheritance Public/Private/Protected • All data and methods in base class (superclass) • Public members of base class: visible to derived are automatically inherited by derived (sub) class class and clients that use it • Changes in base class are automatically propagated • Private members of base class: still not visible to into derived classes derived class or clients • What about the print( ), which exists in both? • The private members are still there inside the derived object! They just aren’t visible • The derived version overrides • What if you wanted to override xpos and ypos? • Protected members in base class: visible in derived class, but not visible to clients. • Sorry, not allowed • Advice: When in doubt, use “protected” (maybe) • So ColorPoint inherits xpos and ypos • If you expect the current class to be extended later • Problem: xpos and ypos are private, right? Need some more rules.... • If you don’t mind exposing implementation details to subclasses 07/17/01 07/17/01 Q-21 Q-22 ColorPoint Implementation ColorPoint Constructor ColorPoint::ColorPoint( double x, double y, Color c ) : Point( x, y ){ Color ColorPoint::getColor(){ color = c; return color; } } • New notation: “ : baseclass(args, …)” calls base class constructor void ColorPoint::print ( ostream& os ){ os << "(" << getX() << ", " << getY() • will initialize base class fields in derived class object << ")/" << color; • Must be placed here } Can’t call directly inside the function • This "initializer" list can also call constructors for member variables 07/17/01 07/17/01 Q-23 Q-24 CSE 143 Q
Recommend
More recommend