24
Objec&ves Inheritance Polymorphism Ø Dispatch Sept 23, 2016 Sprenkle - CSCI209 1

Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Objec&ves• Inheritance• Polymorphism

Ø Dispatch

Sept23,2016 Sprenkle-CSCI209 1

Page 2: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 2

Inheritance• Buildnewclassesbasedonexis&ngclasses

Ø Allowscodereuse• Startwithaclass(parentorsuperclass)• CreateanotherclassthatextendsorspecializestheclassØ Calledthechild,subclassorderivedclassØ Useextends keywordtomakeasubclass

Examples?

Page 3: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 3

Childclass• Inheritsallofparentclass’smethodsandfields

Ø Noteonprivatefields:allareinherited,justcan’taccess

• CanalsooverridemethodsØ Usethesamenameandparameters,butimplementa&onisdifferent

• Addsmethodsorfieldsforaddi/onalfunc/onality• Usesuperobjecttocallparent’smethod

Ø Evenifchildclassredefinesparentclass’smethod

Page 4: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 4

InheritanceRules• Constructorsarenotinherited

Ø Forexample:wewillhavetodefineRooster( String name, int height, double weight ) eventhoughsimilarconstructorinChicken

Page 5: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 5

Rooster class• Couldwriteclassfromscratch,but…• Aroosterisachicken

Ø Butitaddssomethingto(orspecializes)whatachickenis/does

• Classicmarkofinheritance:isarela&onship• Roosterischildclass• Chickenisparentclass

Page 6: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 6

AccessModifiers• public

Ø Anyclasscanaccess• private

Ø Nootherclasscanaccess(includingchildclasses)• Mustuseparentclass’spublicaccessor/mutatormethods

• protectedØ ChildclassescanaccessØ MembersofpackagecanaccessØ Otherclassescannotaccess

Page 7: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

AccessModes

Accessibleto MemberVisibilitypublic protected package private

Definingclass Yes Yes Yes YesClassinsamepackage

Yes Yes Yes No

Subclassindifferentpackage

Yes Yes No No

Non-subclassdifferentpackage

Yes No No No

Sept23,2016 Sprenkle-CSCI209 7

Default (if none specified)

Page 8: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

protected• Accessibletosubclassesandmembersofpackage• Can’tkeepencapsula&on“pure”

Ø Don’twantotherstoaccessfieldsdirectlyØ Maybreakcodeifyouchangeyourimplementa&on

• Assump&on?Ø Someoneextendingyourclasswithprotectedaccessknowswhattheyaredoing

Sept23,2016 Sprenkle-CSCI209 8

Page 9: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 9

AccessModifiers• Ifyou'reuncertainwhichtouse(protected,package,orprivate),usethemostrestric/veØ Changingtolessrestric&velateràeasyØ Changingtomorerestric&veàmaybreakcodethatusesyourclasses

Page 10: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 10

Rooster classpublic class Rooster extends Chicken {

public Rooster( String name, int height, double weight) {// all instance fields inherited// from super classthis.name = name;this.height = height;this.weight = weight;is_female = false;

}

// new functionalitypublic void crow() {… }…

By default calls default super constructor with

no parameters

extends means that Rooster is a child of Chicken

(not one of the examples posted online)

Page 11: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 11

Rooster classpublic class Rooster extends Chicken {

public Rooster( String name, int height, double weight) {

super(name, height, weight, false);}

// new functionalitypublic void crow() { … }

…}

Call to super constructor must be first line in constructor

Page 12: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 12

ConstructorChaining• Constructorautoma-callycallsconstructorofparentclassifnotdoneexplicitlyØ super();

• Whatifparentclassdoesnothaveaconstructorwithnoparameters?Ø Compila&onerrorØ Forceschildclassestocallaconstructorwithparameters

Page 13: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 13

OverridingandNewMethodspublic class Rooster extends Chicken {

// overrides superclass; greater gains@Overridepublic void feed() {

weight += .5;height += 2;

}

// new functionalitypublic void crow() {

System.out.println("Cocka-Doodle-Doo!");}

}

Same method signature as parent class

Specializes the class

Page 14: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 14

InheritanceTree• java.lang.Object

Ø Chicken• Rooster

• Callparentclass’sconstructorfirstØ Knowyouhavefieldsofparentclassbeforeimplemen&ngconstructorforyourclass

Object

Chicken

Rooster

1

2

Page 15: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 15

InheritanceTree• java.lang.Object

Ø Chicken• Rooster

• Nofinalize()chainingØ Shouldcallsuper.finalize() insideoffinalizemethod

Object

Chicken

Rooster

1

2

Page 16: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 16

ShadowingParentClassFields• ChildclasshasfieldwithsamenameasparentclassØ Youprobablyshouldn’tbedoingthis!Ø Butcouldhappen

• Example:moreprecisionforaconstant

field // this class's fieldthis.field // this class's fieldsuper.field // super class's field

Page 17: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 17

Mul&pleInheritance• InPython,itispossibleforaclasstoinherit(orextend)morethanoneparentclassØ Childclasshasthefieldsfrombothparentclasses

• ThisisNOTpossibleinJava.Ø Aclassmayextend(orinheritfrom)onlyoneclass

Page 18: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

POLYMORPHISM&DISPATCH

Sept23,2016 Sprenkle-CSCI209 18

Page 19: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 19

Polymorphism• Polymorphismistheabilityforanobjecttovarybehaviorbasedonitstype

• Youcanuseachildclassobjectwhenevertheprogramexpectsanobjectoftheparentclass

• Objectvariablesarepolymorphic• AChicken objectvariablecanrefertoanobjectofclassChicken, Rooster, Hen,oranyclassthatinheritsfromChicken

Chicken[] chickens = new Chicken[3];chickens[0] = momma;chickens[1] = foghorn;chickens[2] = baby;

We can guess the actual typesBut compiler can’t

Page 20: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 20

Compiler’sBehavior

• Weknowchickens[1]isprobablyaRooster,buttocompiler,it’saChicken sochickens[1].crow(); willnotcompile

Chicken[] chickens = new Chicken[3];chickens[0] = momma;chickens[1] = foghorn;chickens[2] = baby;

Page 21: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 21

Compiler’sBehavior• WhenwerefertoaRooster objectthroughaRoosterobjectvariable,compilerseesitasaRoosterobject

• IfwerefertoaRoosterobjectthroughaChickenobjectvariable,compilerseesitasaChickenobject.

• WecannotassignaparentclassobjecttoaderivedclassobjectvariableØ Ex:RoosterisaChicken,butaChickenisnotnecessarilyaRooster

Rooster r = chicken;

à Object variable determines how compiler sees object.

Page 22: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 22

Polymorphism

Chicken[] chickens = new Chicken[3];chickens[0] = momma;chickens[1] = foghorn;chickens[2] = baby;

chickens[1].feed();

CompilesbecauseChickenhasafeedmethod.But,whichfeedmethodiscalled–

Chicken’sorRooster’s?

Page 23: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 23

Dynamicvs.Sta&cDispatch• Dynamicdispatchisnotnecessarilyapropertyofobject-orientedprogrammingingeneral

• SomeOOPlanguagesusestaCcdispatchØ Typeoftheobjectvariableusedtocallthemethoddetermineswhichversiongetsrun

• Theprimarydifferenceiswhendecisiononwhichmethodtocallismade…Ø Sta&cdispatch(C#)decidesatcompile&meØ Dynamicdispatch(Java,Python)decidesatrun&me

• DynamicdispatchisslowØ  Inmidtolate90s,ac&veresearchonhowtodecrease&me

Page 24: Inheritance Polymorphismsprenkle/cs209/pre_class/06-inheritance.pdf · Sept 23, 2016 Sprenkle - CSCI209 2 Inheritance • Build new classes based on exis&ng classes Ø Allows code

Sept23,2016 Sprenkle-CSCI209 24

InheritanceRules:AccessModifiers

• Why?• Whatwouldhappenifamethodintheparentclassispublic butthechildclass’smethodisprivate?

Access modifiers in child classes• Can make access to child class less restrictive but

not more restrictive