bbm 102 –introduction to programming iibbm102/pdf/w08-abstract_classes.pdf2 today ¢abstract...

46
1 BBM 102 – Introduction to Programming II Spring 2017 Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Abstract Classes and Interfaces

Upload: dinhdat

Post on 26-Mar-2018

222 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

1

BBM102– IntroductiontoProgrammingIISpring 2017

Instructors:AyçaTarhan,FuatAkal,GönençErcan,Vahid Garousi

AbstractClassesandInterfaces

Page 2: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

2

Today

¢ AbstractClasses§ Abstractmethods§ Polymorphismwithabstractclasses§ Exampleproject:PayrollSystem

¢ Interfaces§ WhatisanInterface?§ DefininganInterface§ ImplementinganInterface§ ImplementingMultipleInterfaces§ ExtendingaClassandImplementingInterface(s)§ ExtendinganInterface§ InterfacesasTypes

¢ InterfacesvsAbstractClasses

Page 3: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

3

AbstractClasses

¢ Anabstractclass isaclassthatisdeclaredabstract¢ Anabstractclassmayormaynotincludeabstractmethods.¢ Abstractclassescannotbeinstantiated,buttheycanbesubclassed.

Page 4: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

4

Abstract Classes:Revisiting the Shapes

Shape

Circle Quadrilateral RightTriangle

Square Rectangle

Page 5: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

5

Abstract Classes¢ Shapesallhavecertainstates(forexample:position,orientation,linecolor,fillcolor)andbehaviors(forexample:moveTo,rotate,resize,draw)incommon.

¢ Someofthesestatesandbehaviorsarethesameforallshapes(forexample:position,fillcolor,andmoveTo).

¢ Othersrequiredifferentimplementations(forexample,resizeordraw).

¢ AllShapesmustbeabletodraworresizethemselves;theyjustdifferinhowtheydoit.

Page 6: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

6

AbstractClasses

publicclassShape{privateStringname;

publicShape(Stringname){this.name=name;

}

publicStringgetName(){returnname;

}

publicvoiddraw(){//whatistheshape?// Code...?!Nothing!

}}

publicabstractclassShape{privateStringname;

publicShape(Stringname){this.name=name;

}

publicStringgetName(){returnname;

}

publicabstractvoiddraw();}

Page 7: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

7

AbstractMethods

¢ Anabstractmethod isamethodthatisdeclaredwithoutanimplementation§ withoutbraces,andfollowedbyasemicolon,likethis:

public abstract void draw();

¢ When anabstract class issubclassed,the subclass usuallyprovides implementations for all ofthe abstract methods initsparent class.§ However,if itdoes not,then the subclass must also bedeclared abstract.

Page 8: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

8

AbstractClassespublicclassRightTriangle extendsShape{

privateinta;

publicRightTriangle(Stringname,int a){super(name);this.a=a;

}

publicintgetA(){returna;

}//overrideabstractmethodpublicvoiddraw(){

for(int line=1;line<=a;line++){for(inti=0;i<line;i++){

System.out.print("*");}System.out.println();

}}

}

Page 9: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

9

AbstractClasses

publicabstractclassQuadrilateralextendsShape{

publicQuadrilateral(Stringname){super(name);

}

//stillnothingto draw!publicabstractvoiddraw();

}

publicclassSquareextendsQuadrilateral{privateinta;

publicSquare(Stringname,int a){super(name);this.a=a;

}publicintgetA(){

returna;}

//overrideabstractmethodpublicvoiddraw(){

for(int line=0;line<a;line++){for(intcol=0;col<a;col++){

System.out.print("*");}System.out.println();

}}

}

Page 10: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

10

AbstractClasses

publicclassProgram{

publicstaticvoidmain(String[]args){//compilationerror!:"CannotinstantiatethetypeShape"Shapeshape =newShape("Shape");

//compilationerror!:"CannotinstantiatethetypeQuadrilateral"Quadrilateralquadrilateral=newQuadrilateral("Quadrilateral");

Squares=newSquare("Square",4);s.draw();

Rectangler=newRectangle("Rectangle",3,7);r.draw();

RightTriangle t=newRightTriangle("RightTriangle",5);t.draw();

}}

Page 11: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

11

AbstractClasses

¢ ArepartoftheinheritancehierarchyCircleextendsShapeSquareextends Quadrilateral

¢ Canhaveconstructor(s),butnoobjects oftheseclassescanbecreated

Shapeshape =newShape("Shape");//compilationerror!:"CannotinstantiatethetypeShape“

¢ Classesthatcanbeusedtoinstantiateobjectsarecalledconcreteclasses.

Page 12: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

12

Example-1

Page 13: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

13

Example-2

¢ Imaginethereareseveralinstruments,eitherstringedorwind.¢ Designaclasshierarchyforonlytwotypesofinstruments,guitarsandflutes.

¢ Youhavetodesignyourmodelinawaythatnewinstrumentscanbeadded inthehierarchylateron.

¢ Imaginethereisonlyonefeatureforeachinstrumentatthemoment,whichistheplay feature.

Page 14: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

14

Example-2publicabstractclassInstrument{

protectedStringname;abstractpublicvoidplay();

}

abstractclassStringedInstrument extendsInstrument{protectedint numberOfStrings;

}

Stillabstract

Abstractclass

publicclassGuitarextendsStringedInstrument{

publicvoidplay(){System.out.println(“Guitarisrocking!”);

}}

Page 15: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

15

Example-2

abstractclassWindInstrument extendsInstrument{//features

}

publicclassFluteextendsWindInstrument{

publicvoidplay(){System.out.println(“Fluteisrocking!”);

}}

Page 16: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

16

ExampleProject:PayrollSystem

Page 17: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

17

Overviewoftheclasses

Page 18: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

18

Employee.java(1)

Page 19: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

19

Employee.java(2)

Earningswillbecalculatedinsubclasses

Page 20: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

20

SalariedEmployee.java

Overriddenmethods

Page 21: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

21

HourlyEmployee.java(1)

Page 22: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

22

HourlyEmployee.java(2)

Page 23: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

23

CommissionEmployee.java(1)

Page 24: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

24

CommissionEmployee.java(2)

Page 25: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

25

BasePlusCommissionEmployee.java

Page 26: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

26

PayrollSystemTest.java(1)

Page 27: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

27

PayrollSystemTest.java(2)

Page 28: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

28

Interfaces

GUI

Laptop

LCD/LEDTV

Page 29: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

29

ConceptofInterface

¢ Aninterfaceisacontract.Itguaranteesthatthesystemwillhavecertainfunctionalities.

¢ Aninterfaceisanintegrationpointbetweentwosystems.

¢ Asystemcanhavemanyinterfaces,soitcanbeintegratedtomanyothersystems.

Page 30: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

30

publicinterface Shape{publicabstractvoiddraw();

publicstaticfinaldoublePI=3.14;}

DefininganInterface

¢ Keywordinterface isusedtodefineaninterface

¢ Methodsinaninterfacemustbepublic andabstract,thesekeywordsarecommonly omitted

¢ Interfacescanincludepublic static final variables(constants),thesekeywordsarecommonlyomitted

Noneedtowrite

Page 31: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

31

ImplementinganInterface

¢ Aninterfaceisimplementedbythekeywordimplements

¢ Anyclassimplementinganinterfacemusteitherimplementallmethodsofit,orbedeclaredabstract

publicclassRightTriangle implements Shape {//.....publicvoiddraw(){

for(int line=1;line<=a;line++){for(inti=0;i<line;i++){

System.out.print("*");}System.out.println();

}}

}

Page 32: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

32

ImplementingMultipleInterfaces

¢ Morethanoneinterface canbeimplementedbyaclass.¢ Namesofinterfacesare separated bycomma

Question:Whatifatleasttwointerfacesincludethesamemethoddefinition?

publicclassLedTvimplements Usb,Hdmi,Scart,Vga {

//.....

}

Page 33: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

33

ExtendingaClassandImplementingInterface(s)

publicclassCarextendsVehicleimplementsShape {

publicvoiddraw(){//....

}}

Page 34: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

34

ExtendinganInterface

¢ Itispossibleforaninterfacetoextendanotherinterface

publicinterfaceI1{voidm1();

}

publicclassC2implements I2 {publicvoidm1(){

//...}publicvoidm2(){

//...}

}

publicinterfaceI2extendsI1{voidm2();

}

publicclassC1 implementsI1 {

publicvoidm1(){//...

}}

Page 35: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

35

InterfacesasTypes

¢ Whenyoudefineanewinterface,youaredefininganewreferencedatatype.

¢ Youcanuseinterfacenamesanywhereyoucanuseanyotherdatatypename.

¢ Ifyoudefineareferencevariablewhosetypeisaninterface,anyobjectyouassigntoitmustbeaninstanceofaclassthatimplementstheinterface.

Page 36: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

36

InterfacesasTypes

publicclassProgram{publicstaticvoidmain(String[]args){

Shapeshape;

shape=newSquare(4);shape.draw();

shape=newRectangle(3,7);shape.draw();

shape=newRightTriangle(5);shape.draw();

}}

publicclassProgram{publicstaticvoidmain(String[]args){

Shape[]shapes=newShape[3];shapes[0]=newSquare(5);shapes[1]=newRectangle(2,8);shapes[2]=newRightTriangle(3);for(Shapes:shapes){

drawIt(s);}

}

publicstaticvoiddrawIt(Shapes){s.draw();

}}

Page 37: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

37

ExampleProject:PayrollSystemRevisited

Interfaceimplementation

symbol

Page 38: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

38

Payable.java

Page 39: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

39

Invoice.java(1)

Page 40: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

40

Invoice.java(2)

Page 41: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

41

Employee.java

/*Restoftheclassissameasthepreviousexampleexceptthereisnoearnings() method!*/

Payable interfaceincludesgetPaymentAmount() method,butEmployee classdoesnotimplementit!

Page 42: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

42

SalariedEmployee.java

Page 43: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

43

PayableInterfaceTest.java

Page 44: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

44

Interfaces vs Abstract Classes

Page 45: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

45

Summary

¢ Abstractclassisdefinedwiththekeywordabstract¢ Ifaclassincludesanabstractmethod,itmustbedeclaredasabstract

¢Objectsofabstractclassescannotbecreated¢ Interfaceisdefinedwiththekeywordinterface¢ Aclasscanimplement aninterface,aninterfacecanextend aninterface

¢ Aclasscanimplementmanyinterfaces¢Objectsofinterfacescannotbecreated

Page 46: BBM 102 –Introduction to Programming IIbbm102/pdf/w08-abstract_classes.pdf2 Today ¢Abstract Classes §Abstract methods §Polymorphism with abstract classes §Example project: Payroll

46

Acknowledgements

¢ Thecoursematerialusedtopreparethispresentationismostlytaken/adoptedfromthelistbelow:¢ Java- HowtoProgram,PaulDeitel andHarveyDeitel,PrenticeHall,2012

¢ http://www.javatpoint.com/difference-between-abstract-class-and-interface