07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract...

18
9/23/16 1 Objec-ves Javadocs Inheritance Ø Final methods, fields Abstract Classes Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle - CSCI209 2 “Documentation is a love letter that you write to your future self.” – Damian Conway

Transcript of 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract...

Page 1: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

1

Objec-ves• Javadocs• Inheritance

Ø Finalmethods,fields

• AbstractClasses• Interfaces

Sept26,2016 Sprenkle-CSCI209 1

JAVADOCS

Sept26,2016 Sprenkle-CSCI209 2

“Documentation is a love letter that you write to your future self.” – Damian Conway

Page 2: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

2

Javadocs• Specialcomments,whichareusedtogenerateHTMLdocumenta-on

• Syntax:

• Putbeforeaclass,amethod,orafieldtodescribetherespec-veclass/method/field

Sept26,2016 Sprenkle-CSCI209 3

/** * Comment */

Javadoc• CancontainHTMLsyntaxindescrip-on• Exampleblocktagstodescribeyourcode

Sept26,2016 Sprenkle-CSCI209 4

@param <paramname> <description>@return <description> (includespecialcases)

Page 3: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

3

Examples

Sept26,2016 Sprenkle-CSCI209 5

/** * A simple Java class that models a Chicken. The * state of the chicken is its name, height, and weight * * @author Sara Sprenkle */

/** * @return the height of the chicken, in centimeters */

/** * @param n the String representing the name of the chicken */

Expect these types of comments on all methods from now on

Tags always go last in Javadoc comment

Genera-ngJavadocs• Fromcommand-line:

javadoc [options] [packagenames] [sourcefiles] [@files]

• GeneratesHTMLfilesØ E.g.,Game’sJavadocs

Sept26,2016 Sprenkle-CSCI209 6

Page 4: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

4

Sept26,2016 Sprenkle-CSCI209 7

SummaryofInheritance• Removerepe--vecodebymodelingthe“is-a”hierarchyØ Move“commondenominator”codeuptheinheritancechain

• Don’tuseinheritanceunlessallinheritedmethodsmakesense

• Usepolymorphism

FINALKEYWORD

Sept26,2016 Sprenkle-CSCI209 8

Page 5: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

5

Sept26,2016 Sprenkle-CSCI209 9

Preven-ngInheritance• Some-mes,youdonotwantaclasstoderivefromoneofyourclasses

• Aclassthatcannotbeextendedisknownasafinal class

• Tomakeaclassfinal,simplyaddthekeywordfinal infrontoftheclassdefini-on:

• Exampleoffinal class:System

public final class Rooster extends Chicken { . . .

}

Sept26,2016 Sprenkle-CSCI209 10

Finalmethods• Canmakeamethodfinal

Ø Anyclassderivedfromthisclasscannotoverridethefinal methods

• Bydefault,allmethodsinafinal classarefinal methods.

class Chicken {. . . public final String getName() { . . . }. . .

}

Why would we want to use final?What are possible benefits to us, the compiler, …?

Page 6: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

6

ABSTRACTCLASSES

Sept26,2016 Sprenkle-CSCI209 11

Sept26,2016 Sprenkle-CSCI209 12

AbstractClasses• Somemethodsdefined,othersnotdefined

Ø Par-alimplementa-on

• Classesinwhichnotallmethodsareimplementedareabstract classes Ø public abstract class ZooAnimal

• BlankmethodsarelabeledasabstractØ public abstract void exercise(Environment env);

Page 7: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

7

Sept26,2016 Sprenkle-CSCI209 13

AbstractClasses• Anabstractclasscannotbeinstan-ated

Ø i.e.,can’tcreateanobjectofthatclassØ Butcanhaveaconstructor!

• Childclassofanabstractclasscanonlybeinstan-atedifitoverridesandimplementseveryabstractmethodofparentclassØ Ifchildclassdoesnotoverrideallabstractmethods,itisalsoabstract

Sept26,2016 Sprenkle-CSCI209 14

AbstractClasses• static,private,andfinalmethodscannotbeabstractØ B/ccannotbeoverriddenbyachildclass

• final classcannotcontainabstractmethods

• AclasscanbeabstractevenifithasnoabstractmethodsØ Usewhenimplementa-onisincompleteandismeanttoserveasaparentclassforclass(es)thatcompletetheimplementa-on

• CanhavearrayofobjectsofabstractclassØ JVMwilldodynamicdispatchformethods

Why?

Page 8: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

8

Sept26,2016 Sprenkle-CSCI209 15

Examplesofabstractclasses• Example1:

Ø java.net.SocketØ java.net.SSLSocket (abstract)

• Example2:Ø java.util.Calendar (abstract)Ø java.util.GregorianCalendar

Sept26,2016 Sprenkle-CSCI209 16

Summary:DefiningAbstractClasses➨ Defineaclassasabstractwhenhavepar%alimplementa%on

Page 9: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

9

INTERFACES

Sept26,2016 Sprenkle-CSCI209 17

Sept26,2016 Sprenkle-CSCI209 18

Interfaces• Purespecifica-on,noimplementa-on

Ø Asetofrequirementsforclassestoconformto

• Classescanimplementoneormoreinterfaces

Page 10: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

10

Sept26,2016 Sprenkle-CSCI209 19

ExampleofanInterface• WecancallArrays.sort(array)

• Arrays.sortsortsarraysofanyobjectclassthatimplementstheComparable interface

• ClassesthatimplementComparable mustprovideawaytodecideifoneobjectislessthan,greaterthan,orequaltoanotherobject

Sept26,2016 Sprenkle-CSCI209 20

java.lang.Comparable

• Anyobjectthatis(inherits)Comparable musthaveamethodnamedcompareTo()

• Returns:Ø Returnanega-veintegerifthethisobjectislessthantheobjectpassedasaparameter

Ø Returnaposi-veintegerifthethisobjectisgreaterthantheobjectpassedasaparameter

Ø Returna0ifthetwoobjectsareequal

public interface Comparable {int compareTo(Object other);

}

Page 11: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

11

Sept26,2016 Sprenkle-CSCI209 21

ComparableInterfaceAPI/Javadoc• SpecifieswhatthecompareTo()methodshoulddo

• SayswhichJavalibraryclassesimplementComparable

http://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html

Sept26,2016 Sprenkle-CSCI209 22

Implemen-nganInterface• Intheclassdefini-on,specifythattheclasswillimplement thespecificinterface

• Provideadefini-onforallmethodsspecifiedininterface

public class Chicken implements Comparable

How to determine Chicken order?

Page 12: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

12

Sept26,2016 Sprenkle-CSCI209 23

Comparable Chickens Oneway:orderbyheight

What if otherObject is not a Chicken?

public class Chicken implements Comparable { . . . public int compareTo(Object otherObject) { Chicken other = (Chicken)otherObject; if (height < other.getHeight() )

return –1;if (height > other.getHeight())

return 1;return 0;// simpler: return height-other.getHeight()

}}

Sept26,2016 Sprenkle-CSCI209 24

InterfaceSummary• Containonlyobject(notclass)methods• Allmethodsarepublic

Ø Impliedifnotexplicit

• Fieldsareconstantsthatarestaticandfinal

• Aclasscanimplementmul-pleinterfacesØ Separatedbycommasindefini-on

Page 13: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

13

Sept26,2016 Sprenkle-CSCI209 25

Tes-ngforInterfaces

• Usetheinstanceof operatortoseeifanobjectimplementsaninterfaceØ e.g.,todetermineifanobjectcanbecomparedtoanotherobjectusingtheComparableinterface

if (obj instanceof Comparable) { // runs if obj is an object variable of a class// that implements the Comparable interface

}else {

// runs if it does not implement the interface }

Sept26,2016 Sprenkle-CSCI209 26

InterfaceObjectVariables• Canuseanobjectvariabletorefertoanobjectofanyclassthatimplementsaninterface

• Usingthisobjectvariable,canonlyaccesstheinterface’smethods

• Forexample…

public void aMethod(Object o) {…if (obj instanceof Comparable) {

Comparable comp = (Comparable) obj; boolean res = comp.compareTo(obj2);

}}

Page 14: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

14

Sept26,2016 Sprenkle-CSCI209 27

InterfaceDefini-ons

• Interfacemethodsarepublic bydefaultØ Donotneedtospecifymethodsaspublic

public interface Comparable {int compareTo(Object other);

}

Sept26,2016 Sprenkle-CSCI209 28

InterfaceDefini-onsandInheritance• Canextendinterfaces

Ø Allowsachainofinterfacesthatgofromgeneraltomorespecific

• Forexample,defineaninterfaceforanobjectthatiscapableofmoving:

public interface Movable {void move(double x, double y);

}

Page 15: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

15

Sept26,2016 Sprenkle-CSCI209 29

InterfaceDefini-onsandInheritance• ApoweredvehicleisalsoMovable

Ø MustalsohaveamilesPerGallon() method,whichwillreturnitsgasmileage

public interface Powered extends Movable {double milesPerGallon();

}

Sept26,2016 Sprenkle-CSCI209 30

ConstantsinanInterface• Ifavariableisspecifiedinaninterface,itisautoma-callyaconstant:Ø public static final variable

• AnobjectthatimplementsPoweredinterfacehasaconstantSPEED_LIMITdefined

public interface Powered extends Movable {double milesPerGallon();double SPEED_LIMIT = 95;

}

Page 16: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

16

Sept26,2016 Sprenkle-CSCI209 31

InterfaceDefini-onsandInheritance• PoweredinterfaceextendsMovableinterface• AnobjectthatimplementsPoweredinterfacemustsa-sfyallrequirementsofthatinterfaceaswellastheparentinterface.Ø APoweredobjectmusthaveamilesPerGallon()andmove() method

Sept26,2016 Sprenkle-CSCI209 32

Mul-pleInterfaces• Aclasscanimplementmul-pleinterfaces

Ø Mustfulfilltherequirementsofeachinterface

• ButNOTpossiblewithinheritanceØ Aclasscanonlyextend(orinheritfrom)oneclass

public final class String implementsSerializable, Comparable, CharSequence { …

Page 17: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

17

Sept26,2016 Sprenkle-CSCI209 33

BenefitsofInterfaces• ??

UsinganInterfaceorAbstractClass

Sept26,2016 Sprenkle-CSCI209 34

When should we use an interface or an abstract class?

Page 18: 07-abstract and interfacessprenkle/cs209/pre_class/07-abstract_and_interfac… · • Abstract Classes • Interfaces Sept 26, 2016 Sprenkle - CSCI209 1 JAVADOCS Sept 26, 2016 Sprenkle

9/23/16

18

AbstractClassesandInterfaces• ImportantstructuresinJava

Ø Makecodeeasiertochange

• Willreturnto/applytheseideasthroughoutthecourse

• ConceptsareusedinmanylanguagesbesidesJava

Sept26,2016 Sprenkle-CSCI209 35