introduction to inheritance fall 2005 oopd john anthony

28
Introduction to Introduction to Inheritance Inheritance Fall 2005 OOPD Fall 2005 OOPD John Anthony John Anthony

Post on 21-Dec-2015

221 views

Category:

Documents


1 download

TRANSCRIPT

Introduction to Introduction to Inheritance Inheritance

Fall 2005 OOPDFall 2005 OOPDJohn AnthonyJohn Anthony

Remember our Team Remember our Team ExampleExample

What is itWhat is itThe property of objects by which instances of a class The property of objects by which instances of a class can have access to data and method definitions can have access to data and method definitions contained in a previously defined class, without contained in a previously defined class, without those definitions being restated.those definitions being restated.

Inheritance is a "parent/child" Inheritance is a "parent/child" relationship between two classes, the relationship between two classes, the "superclass" (parent) and "subclass" "superclass" (parent) and "subclass" (child).(child).

The child "inherits" instance variables The child "inherits" instance variables and methods from the parent.and methods from the parent.

Reasons to Use Reasons to Use InheritanceInheritance

As a means of As a means of code reuse code reuse (extension)(extension)

As a means of As a means of concept reuse concept reuse (overriding)(overriding) Supports the Supports the

notion of loose notion of loose couplingcoupling

Let’s Collapse the Let’s Collapse the Hierarchy Into One TypeHierarchy Into One Type

Here is what the code may Here is what the code may look like…look like…

public void noInheritanceExample2() {Team aTeam = new Team(1);

TeamMember genericMember = new TeamMember(TeamMember.TEAM_MEMBER);aTeam.addTeamMember(genericMember);

TeamMember developer = new TeamMember(TeamMember.INNOVATION_LAB_DEVELOPER);aTeam.addTeamMember(developer);

//or shortcutaTeam.addTeamMember(new TeamMember(TeamMember.INNOVATION_LAB_ARCHITECT));

//display the burn ratesIterator teamMembers = aTeam.retrieveTeamMembers().iterator();while(teamMembers.hasNext()) {

TeamMember member = (TeamMember)teamMembers.next();if(member.getMemberType() == TeamMember.TEAM_MEMBER) {

System.out.println("Burn Rate = " + member.calculateBurnRate());}else if(member.getMemberType() == TeamMember.INNOVATION_LAB_DEVELOPER) {

System.out.println("Burn Rate = " + member.calculateBurnRateForDeveloper());}else {

System.out.println("Burn Rate = " + member.CalculateBurnRateForArchitect());}

}

}

Let’s Create a Class for Let’s Create a Class for Each Team Member TypeEach Team Member Type

Here is what the code may Here is what the code may look like…look like…

public void noInheritanceExample1() {Team aTeam = new Team(1);aTeam.addTeamMember(new TeamMember());aTeam.addArchitect(new InnovationLabArchitect());aTeam.addDeveloper(new InnovationLabDeveloper());

//display burn rate for each team member.Iterator teamMembers = aTeam.retrieveTeamMembers().iterator();while(teamMembers.hasNext()) {

Object someMember = teamMembers.next();if( someMember instanceof InnovationLabArchitect) {

InnovationLabArchitect architect = (InnovationLabArchitect)someMember;System.out.println(architect.calculateBurnRate());

}else if( someMember instanceof InnovationLabDeveloper) {

InnovationLabDeveloper developer = (InnovationLabDeveloper)someMember;System.out.println(developer.calculateBurnRate());

}else {

TeamMember member = (TeamMember)someMember;System.out.println(member.calculateBurnRate());

}}

}

Now with InheritanceNow with Inheritance

Here is what the code may Here is what the code may look likelook like

public void inheritanceExample() {Team aTeam = new Team(1);

TeamMember genericMember = new TeamMember();aTeam.addTeamMember(genericMember);

aTeam.addTeamMember(new InnovationLabArchitect());aTeam.addTeamMember(new InnovationLabDeveloper());

Iterator teamMembers = aTeam.retrieveTeamMembers().iterator();

while(teamMembers.hasNext()) {TeamMember member = (TeamMember)teamMembers.next();System.out.println("Burn Rate = " + member.calculateBurnRate());

}}

Liskov Substitution Liskov Substitution Principle (subtyping) Principle (subtyping)

If S is a subtype of T, then objects of type T may If S is a subtype of T, then objects of type T may be replaced with objects of type S without be replaced with objects of type S without altering the correctness of the program.altering the correctness of the program.

For a function f(A a), if f satisfies its specification when passed an object whose actual type is A, f also satisfies its specification when passed an object whose actual type is B.

public void addTeamMember(TeamMember member) {…}

What happens when an instance of InnovationLabArchitect is passed?

SubclassSubclass

java.util.Vector

java.util.Stackpublic Object peek();

Public Object pop();

Public Object elementAt(int index)

Vector myStack = new Stack();

PolymorphismPolymorphism

PolymorphismPolymorphism – the ability to take different – the ability to take different forms. forms.

In OO, it refers to the ability of executing different In OO, it refers to the ability of executing different operations (methods) in response to the same operations (methods) in response to the same message.message.

Types of Polymorphism:Types of Polymorphism: Polymorphic variable & functionPolymorphic variable & function Overloading Overloading (later)(later) Overriding Overriding (later)(later) Generics (parameterized types) Generics (parameterized types) (later)(later)

Polymorphic VariablePolymorphic Variable

A variable (or reference) that can be A variable (or reference) that can be attached to more than one type of attached to more than one type of object.object.

TeamMember member = new TeamMember();TeamMember member = new TeamMember();

InnovationLabArchitect architect = new InnovationLabArchitectInnovationLabArchitect architect = new InnovationLabArchitect ();();

polymorphic variable

non polymorphic variable

Polymorphic AttachmentPolymorphic Attachment

What is the difference between a What is the difference between a reference and an object?reference and an object?TeamMember member = new TeamMember();TeamMember member = new TeamMember();InnovationLabArchitect architect = new InnovationLabArchitectInnovationLabArchitect architect = new InnovationLabArchitect ();();

TeamMember

InnovationLabArchitect

membermember

architectarchitect

before

after

member = architect;member = architect;

ExampleExampleI

public static void main(String args[]) { TeamMember member = new TeamMember(); System.out.println(member.toString());

InnovationLabArchitect architect = new InnovationLabArchitect(); System.out.println(architect.toString());

member = architect; System.out.println(member.toString());

architect = (InnovationLabArchitect)member; System.out.println(architect.toString());}

public String toString() { return "I am a TeamMember!";}

TeamMemberpublic String toString() { return "I am a Lab Architect!";}

InnovationLabArchitect

Polymorphic FunctionPolymorphic Function

A function that can take objects of A function that can take objects of various classes (or types). various classes (or types).

public void addTeamMember(InnovationLabArchitect member) {…}

vs.

public void addTeamMember(TeamMember member) {…}

Overriding (intro)Overriding (intro)

A method in a subclass with the same signature A method in a subclass with the same signature and return type as a method in the superclass and return type as a method in the superclass overridesoverrides the superclass's method the superclass's method..

Rules for OverridingRules for Overriding1.1. Method name must matchMethod name must match

2.2. Some number and type (or subtype) of parametersSome number and type (or subtype) of parameters

3.3. Same return value (or subclass)Same return value (or subclass)

4.4. Same throws clause (or subclass)Same throws clause (or subclass)

5.5. Access modifier can allow or more access but not less.Access modifier can allow or more access but not less.

6.6. Parent method must not be finalParent method must not be final

Overloading (intro)Overloading (intro)

Occurs when a class declares two or Occurs when a class declares two or more methods with the same name more methods with the same name but different signatures.but different signatures.

When a message is sent to an object or When a message is sent to an object or class with overloaded methods, the class with overloaded methods, the method with the method with the best matching signaturebest matching signature is the one that is used ("invoked"). is the one that is used ("invoked").

Overloading (intro) con’tOverloading (intro) con’t

Signature can differ by order, Signature can differ by order, number, and type of arguments.number, and type of arguments.

public void foo(String x, int y) { }

public void foo(int y, String x) { }

public String foo(int y, String x) { return null; }

public void foo(int y, String x, int z) { }

While two lines will generate a duplicate method error?

Forms of InheritanceForms of Inheritance

Subclassing for specialization Subclassing for specialization (subtyping)(subtyping)

Subclassing for specificationSubclassing for specification Subclassing for constructionSubclassing for construction Subclassing for generalizationSubclassing for generalization Subclassing for extensionSubclassing for extension Subclassing for limitationSubclassing for limitation Subclassing for varianceSubclassing for variance Subclassing for combinationSubclassing for combination

Subclassing for specialization Subclassing for specialization (subtyping)(subtyping)

The subclass is a specialized form the The subclass is a specialized form the parent class.parent class.

Most common use (and perhaps best use of) Most common use (and perhaps best use of) inheritance.inheritance.

Satisfies the substitution principle.Satisfies the substitution principle. Consider the InnovationLabArchitect as a Consider the InnovationLabArchitect as a

subclass as TeamMember. subclass as TeamMember. calculateBurnRate() calculateBurnRate()

Subclassing for Subclassing for specificationspecification

Subclass adheres to the contract as specified by the Subclass adheres to the contract as specified by the parent (i.e. does not add additional features).parent (i.e. does not add additional features).

provides implementations for abstract or deferred methods in the parent class.provides implementations for abstract or deferred methods in the parent class. subclasses in this cases are not specialization of the parent class but rather subclasses in this cases are not specialization of the parent class but rather

realizations of an incomplete implementation.realizations of an incomplete implementation. All classes that implement interfaces are Subclassing for specification.All classes that implement interfaces are Subclassing for specification.

java.util.AbstractList

java.util.ArrayList

java.util.AbstractCollectionpublic abstract int size()

public abstract int size(), public abstract Object get(int index)

Subclassing for Subclassing for constructionconstruction

Used when there is functionality in the parent Used when there is functionality in the parent class that the child class desires. However, class that the child class desires. However, the parent class is not a supertype of the the parent class is not a supertype of the child class.child class.

Consider inheriting from a List class in order to build a Set.Consider inheriting from a List class in order to build a Set.

What do you think about this?What do you think about this?

Does this break the principle of substitution?Does this break the principle of substitution?

What are the advantages to form of inheritance?What are the advantages to form of inheritance?

Subclassing for Subclassing for generalizationgeneralization

The subclass offers The subclass offers more features more features (behavior or state) (behavior or state) than the parent than the parent class.class.

Opposite of subclassing for Opposite of subclassing for specializationspecialization

Often used when the parent class Often used when the parent class cannot be modified (i.e. use of cannot be modified (i.e. use of frameworks).frameworks).

Usually results in overriding a Usually results in overriding a feature from the parent class.feature from the parent class.

Override *Drivers() features to throw an exception if called.

Subclassing for Subclassing for extensionextension

The subclass The subclass adds adds additional additional features to the features to the parent class.parent class.

Since parent Since parent features are not features are not altered, subclasses altered, subclasses are always are always subtypes.subtypes.

Subclassing for Subclassing for limitationlimitation

Seeks to limit the behavior of the Seeks to limit the behavior of the parent class by overriding parent parent class by overriding parent features.features.

Implementer may override a method Implementer may override a method and then throw an exception when the and then throw an exception when the “restricted” method is called.“restricted” method is called.

Breaks the goal of substitutionBreaks the goal of substitution Example: create stack from dequeExample: create stack from deque

Subclassing for Subclassing for combinationcombination

We call this multiple inheritance…We call this multiple inheritance…

Looks to combine the features of two parent Looks to combine the features of two parent classes into one.classes into one.

Consider Consider InnovationLabArchitectInnovationLabArchitect inheriting from inheriting from both a both a TeamMemberTeamMember and and InnovationLabDeveloperInnovationLabDeveloper class.class.