bbm 102 –introduction to programming iibbm102/pdf/w08-abstract_classes.pdf2 today ¢abstract...
TRANSCRIPT
1
BBM102– IntroductiontoProgrammingIISpring 2017
Instructors:AyçaTarhan,FuatAkal,GönençErcan,Vahid Garousi
AbstractClassesandInterfaces
2
Today
¢ AbstractClasses§ Abstractmethods§ Polymorphismwithabstractclasses§ Exampleproject:PayrollSystem
¢ Interfaces§ WhatisanInterface?§ DefininganInterface§ ImplementinganInterface§ ImplementingMultipleInterfaces§ ExtendingaClassandImplementingInterface(s)§ ExtendinganInterface§ InterfacesasTypes
¢ InterfacesvsAbstractClasses
3
AbstractClasses
¢ Anabstractclass isaclassthatisdeclaredabstract¢ Anabstractclassmayormaynotincludeabstractmethods.¢ Abstractclassescannotbeinstantiated,buttheycanbesubclassed.
4
Abstract Classes:Revisiting the Shapes
Shape
Circle Quadrilateral RightTriangle
Square Rectangle
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.
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();}
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.
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();
}}
}
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();
}}
}
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();
}}
11
AbstractClasses
¢ ArepartoftheinheritancehierarchyCircleextendsShapeSquareextends Quadrilateral
¢ Canhaveconstructor(s),butnoobjects oftheseclassescanbecreated
Shapeshape =newShape("Shape");//compilationerror!:"CannotinstantiatethetypeShape“
¢ Classesthatcanbeusedtoinstantiateobjectsarecalledconcreteclasses.
12
Example-1
13
Example-2
¢ Imaginethereareseveralinstruments,eitherstringedorwind.¢ Designaclasshierarchyforonlytwotypesofinstruments,guitarsandflutes.
¢ Youhavetodesignyourmodelinawaythatnewinstrumentscanbeadded inthehierarchylateron.
¢ Imaginethereisonlyonefeatureforeachinstrumentatthemoment,whichistheplay feature.
14
Example-2publicabstractclassInstrument{
protectedStringname;abstractpublicvoidplay();
}
abstractclassStringedInstrument extendsInstrument{protectedint numberOfStrings;
}
Stillabstract
Abstractclass
publicclassGuitarextendsStringedInstrument{
publicvoidplay(){System.out.println(“Guitarisrocking!”);
}}
15
Example-2
abstractclassWindInstrument extendsInstrument{//features
}
publicclassFluteextendsWindInstrument{
publicvoidplay(){System.out.println(“Fluteisrocking!”);
}}
16
ExampleProject:PayrollSystem
17
Overviewoftheclasses
18
Employee.java(1)
19
Employee.java(2)
Earningswillbecalculatedinsubclasses
20
SalariedEmployee.java
Overriddenmethods
21
HourlyEmployee.java(1)
22
HourlyEmployee.java(2)
23
CommissionEmployee.java(1)
24
CommissionEmployee.java(2)
25
BasePlusCommissionEmployee.java
26
PayrollSystemTest.java(1)
27
PayrollSystemTest.java(2)
28
Interfaces
GUI
Laptop
LCD/LEDTV
29
ConceptofInterface
¢ Aninterfaceisacontract.Itguaranteesthatthesystemwillhavecertainfunctionalities.
¢ Aninterfaceisanintegrationpointbetweentwosystems.
¢ Asystemcanhavemanyinterfaces,soitcanbeintegratedtomanyothersystems.
30
publicinterface Shape{publicabstractvoiddraw();
publicstaticfinaldoublePI=3.14;}
DefininganInterface
¢ Keywordinterface isusedtodefineaninterface
¢ Methodsinaninterfacemustbepublic andabstract,thesekeywordsarecommonly omitted
¢ Interfacescanincludepublic static final variables(constants),thesekeywordsarecommonlyomitted
Noneedtowrite
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();
}}
}
32
ImplementingMultipleInterfaces
¢ Morethanoneinterface canbeimplementedbyaclass.¢ Namesofinterfacesare separated bycomma
Question:Whatifatleasttwointerfacesincludethesamemethoddefinition?
publicclassLedTvimplements Usb,Hdmi,Scart,Vga {
//.....
}
33
ExtendingaClassandImplementingInterface(s)
publicclassCarextendsVehicleimplementsShape {
publicvoiddraw(){//....
}}
34
ExtendinganInterface
¢ Itispossibleforaninterfacetoextendanotherinterface
publicinterfaceI1{voidm1();
}
publicclassC2implements I2 {publicvoidm1(){
//...}publicvoidm2(){
//...}
}
publicinterfaceI2extendsI1{voidm2();
}
publicclassC1 implementsI1 {
publicvoidm1(){//...
}}
35
InterfacesasTypes
¢ Whenyoudefineanewinterface,youaredefininganewreferencedatatype.
¢ Youcanuseinterfacenamesanywhereyoucanuseanyotherdatatypename.
¢ Ifyoudefineareferencevariablewhosetypeisaninterface,anyobjectyouassigntoitmustbeaninstanceofaclassthatimplementstheinterface.
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();
}}
37
ExampleProject:PayrollSystemRevisited
Interfaceimplementation
symbol
38
Payable.java
39
Invoice.java(1)
40
Invoice.java(2)
41
Employee.java
/*Restoftheclassissameasthepreviousexampleexceptthereisnoearnings() method!*/
Payable interfaceincludesgetPaymentAmount() method,butEmployee classdoesnotimplementit!
42
SalariedEmployee.java
43
PayableInterfaceTest.java
44
Interfaces vs Abstract Classes
45
Summary
¢ Abstractclassisdefinedwiththekeywordabstract¢ Ifaclassincludesanabstractmethod,itmustbedeclaredasabstract
¢Objectsofabstractclassescannotbecreated¢ Interfaceisdefinedwiththekeywordinterface¢ Aclasscanimplement aninterface,aninterfacecanextend aninterface
¢ Aclasscanimplementmanyinterfaces¢Objectsofinterfacescannotbecreated
46
Acknowledgements
¢ Thecoursematerialusedtopreparethispresentationismostlytaken/adoptedfromthelistbelow:¢ Java- HowtoProgram,PaulDeitel andHarveyDeitel,PrenticeHall,2012
¢ http://www.javatpoint.com/difference-between-abstract-class-and-interface