The child gets it all.. Factor out common behavior parent class implements behavior needed by...

Post on 18-Dec-2015

213 views 0 download

transcript

The child gets it all.

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

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

An object of the subclass can be used anywhere that an object of the superclass is expectedIn a program, if all objects of the superclass are replaced by objects from a subclass, the program should still work correctly.

ORSubtypes must be substitutable for their base types

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);}

}

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

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 Class Visibility in Child Class

public ToString( ) public ToString( )

protected setName( ) protected or public OK

private getRadix( ): int anything -- private method is statically bound, visible only inside parent class.

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( )

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 samepublic string ToString() { return name+" "+ID; }

// Illegal! (1) less visible, (2) change typeprotected string getID() { return ID; }

}

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

}}

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 behaviorpublic void addToCredits(int n) { credits += n; }public void getCredits( ) { return credits; }

}

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

Apply the “is a” rule

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

Tub1

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.

Subclass doesn't add significant extension or specializationExample: a library has several types of recordings: Jazz Recording, Classical Recording, Pop Recording, ...Recordings may be Tape or CDROM

. . .

Recording

JazzRecordingClassicalRecording PopRecording

JazzTapeRecordingJazzCDROMRecording

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

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

StudentEnrollment1 *

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

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

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

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.

GAME OBJECT TARGET OBJECT

Right click on the library(engine) project > Add > New Item

Pick “Class”

TARGET OBJECT BASE OBJECT

What happens if you don’t?

CompileRemove the reference from the

game projectAdd the reference back in (just to

make sure the changes are in the game)