Download presentation
Presentation is loading. Please wait.
Published byAlaina Wilkins Modified over 9 years ago
1
The child gets it all.
2
Factor out common behavior parent class implements behavior needed by children guarantee that all subclasses have the characteristics promotes code re-use, avoids duplication & errors Specialization child class redefines behavior of the parent Extension child class adds new attributes or behavior
3
Provide common behavior implement once in the superclass, all children inherit it Example: all bank accounts have account ID, owner, balance BankAccount # accountName # accountID # balance + deposit( ) : void + withdraw( ) : void + getBalance( ) : double + getAcctName( ) : String...etc... CheckingAccount + CheckingAccount( ) + withdraw( ) : void + toString( ) : String SavingAccount + SavingAccount( ) + withdraw( ) : void + toString( ) : String
4
An object of the subclass can be used anywhere that an object of the superclass is expected In a program, if all objects of the superclass are replaced by objects from a subclass, the program should still work correctly. OR Subtypes must be substitutable for their base types
5
A subclass can override (redefine) a method inherited from the parent, in order to specialize the behavior. The subclass specializes the behavior for its own needs public class Person { protected string name; public string ToString() { return name; } } public class Student : Person { protected string studentID; // redefine ToString() to return our ID, too. public string ToString() { return string.Format(“{0} {1} “, name, studentID); }
6
Bank accounts have different rules for deposit and withdraw, so we specialize (redefine) these methods in SavingAccount and CheckingAccount BankAccount + deposit( ) : void + withdraw( ) : void + getBalance( ) : double + getAcctName( ) : String...etc... CheckingAccount + deposit( ) : void + withdraw( ) : void SavingAccount + deposit( ) : void + withdraw( ) : void
7
A subclass cannot "reduce visibility" of a method it redefines from parent. Example: Object ToString() is public. A subclass cannot define its own ToString() to be protected or private. assign weaker access permissions is OK. Visibility in Parent ClassVisibility in Child Classpublic ToString( ) protected setName( )protected or public OK private getRadix( ): int anything -- private method is statically bound, visible only inside parent class.
8
Why these access rules? Its a consequence of the Substitution Principle "An object of a child class can be substituted any where that an object of the parent class is expected" Example: the Greeter class expects a Person object and issues a greeting: public class Greeter { public static void greet( Person p ) { Console.WriteLine("Hello " + p.ToString() ) } Person joe = new Person("Joe Nerd"); Greeter.greet( joe ); joe = new Student("Joe Scholar", "12345678"); Greeter.greet( joe ); Student ToString( ) must be at least as visible as Person ToString( )
9
public class Person { protected string name; protected long ID; public long getID() { return ID; } } public class Student : Person { private string ID;// OK to redefine ID! // OK to redefine method: visibility & type same public string ToString() { return name+" "+ID; } // Illegal! (1) less visible, (2) change type protected string getID() { return ID; } }
10
Parent's data members and methods are not replaced by child's members, they are simply shadowed. Use “ base " to access parent's members (except private ones). (in java the keyword for this is “super”) public class Person { protected string name; protected long ID; public string ToString() { return name; } } public class Student : Person { private string ID;// OK to redefine ID! public string ToString() { return name + " " + base.ID; // parent's ID }
11
A subclass can define new behavior that the superclass does not have. A subclass can also define new attributes. public class Person { protected string name; public string ToString() { return name; } } public class Student : Person { protected int credits; // new attribute // new behavior public void addToCredits(int n) { credits += n; } public void getCredits( ) { return credits; } }
12
A simple test for whether inheritance is reasonable is the "is a" rule. a Student is a Person Student extends Person a Button is a WebControl Button extends System.Web.UI.WebControls
13
Apply the “is a” rule
15
In the case of a Tub, we would say: "a Bathroom has a Tub" "has a" means that something should be an attribute "has a" indicates an association. UML uses an open arrowhead for association Bathroom - items : Tub Tub 1
16
The "is a" rule does not always indicate inheritance. Barak Obama is a Person BarakObama is an instance of the Person class A C # book is a Book Java book doesn't specialize any behavior of Book. This is a classifier that can be modeled using an attribute. A Fraction is Comparable Describes a kind of behavior that Fractions possess. Model this using an interface.
17
Subclass doesn't add significant extension or specialization Example: a library has several types of recordings: Jazz Recording, Classical Recording, Pop Recording,... Recordings may be Tape or CDROM... Recording JazzRecordingClassicalRecordingPopRecording JazzTapeRecordingJazzCDROMRecording
18
Don't use a subclass in situations where an object may need to change class during its life time. Example: Full-time and Part-time students have different requirements and behavior. Should we model this using inheritance? Student PartTimeStudentFullTimeStudent
19
A student could change from Full-time to Part-time... and back again! Full-time or part-time is a role or status. A Part-time student may have some behavior that is different from Full-time student. Model this using an attribute of Student that references an object of the appropriate status. attendance PartTimeFullTime Student Enrollment 1 *
20
C++ has multiple inheritance: subclasses can "mix in" the properties of several parent classes. class iostream: public istream, public ostream { public: iostream( streambuf* ); virtual ~iostream(); protected: iostream( ); } istream ostream iostream
21
Java and C# do not allow multiple inheritance. In many situations interfaces can substitute for use of multiple inheritance. public class Student extends Person, Thread {... } Error: no multiple inheritance public class Student extends Person implements IRunnable {... } Runnable interface for Threaded application
22
Java and C# do not allow multiple inheritance. In many situations interfaces can substitute for use of multiple inheritance. public class Student : Person, Thread {... } Error: no multiple inheritance public class Student : Person, IRunnable {... } Runnable interface for Threaded application
23
In our game we have 2 objects that are very similar If we take what is similar and create a base object, then we eliminate duplication of code.
24
GAME OBJECTTARGET OBJECT
25
Right click on the library(engine) project > Add > New Item Pick “Class”
28
TARGET OBJECTBASE OBJECT
29
What happens if you don’t?
34
Compile Remove the reference from the game project Add the reference back in (just to make sure the changes are in the game)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.