Mobile Development WorkshopObject-Oriented Programming Our world consists of objects (people, trees,...
Transcript of Mobile Development WorkshopObject-Oriented Programming Our world consists of objects (people, trees,...
MobileDevelopmentWorkshopDAY1: INTRODUCTIONTOJAVA
OverviewMorningsession◦ Computerhardware,software,andprogramming languages◦ TheJavaprogramming language◦ Simple Javastatements◦ Data,variables,andtypes◦ Classes,objects,andmethods
Afternoonsession◦ Controlflow◦ Conditional statements◦ Loops
HardwareandSoftwareComputersystemsconsistofhardware andsoftware.◦ Hardwareincludesthetangible partsofcomputersystems.◦ Softwareincludesprograms - setsofinstructionsforthecomputertofollow.
Familiaritywithhardwarebasicshelpsusunderstandsoftware.
MemoryMemoryholds◦ programs◦ dataforthecomputer toprocess◦ theresultsof intermediateprocessing.
Twokindsofmemory◦ mainmemory◦ auxiliarymemory
Bits,Bytes,andAddressesAbit isadigitwithavalueofeither0or1.Abyte consistsof8bits.Eachbyteinmainmemoryresidesatanumberedlocationcalleditsaddress.
MainMemoryFigure1.1
ProgramsAprogram isasetofinstructionsforacomputertofollow.Weuseprogramsalmostdaily(email,wordprocessors,videogames,bankATMs,etc.).Followingtheinstructionsiscalledrunning orexecuting theprogram.
RunningaProgram
ProgrammingLanguagesHigh-level languagesarerelativelyeasytouse◦ Java,C#,C++,VisualBasic,Python,Ruby.
Unfortunately,computerhardwaredoesnotunderstandhigh-levellanguages.◦ Therefore,ahigh-levellanguageprogrammustbetranslatedintoalow-levellanguage.
CompilersAcompilertranslatesaprogramfromahigh-levellanguagetoalow-levellanguagethecomputercanrun.Youcompile aprogrambyrunningthecompileronthehigh-level-languageversionoftheprogramcalledthesourceprogram.Compilersproducemachine- or assembly-languageprogramscalledobjectprograms.
JavaByte-CodeTheJavacompiler doesnottranslateaJavaprogramintoassemblylanguage ormachinelanguage foraparticularcomputer.Instead,ittranslatesaJavaprogramintobyte-code.◦ Byte-codeisthemachinelanguage forahypotheticalcomputer(or interpreter)calledtheJavaVirtualMachine.
CompilingandRunningaProgram
WritingourfirstJavaProgramsWriteaprogramthatoperateslikethis:
Samplescreenoutput
PrintingtothescreenSystem.out.println (“Whatever you want to print”);
System.out isanobjectforsendingoutputtothescreen.println isamethodtoprintwhateverisinparenthesestothescreen.
PrintingtothescreenThe object performs an action when you invoke or call one of its methodsobjectName.methodName(argumentsTheMethodNeeds);
Object-OrientedProgrammingOurworldconsistsofobjects (people,trees,cars,cities,airlinereservations,etc.).
Objectscanperformactionswhichaffectthemselvesandotherobjectsintheworld.
Object-orientedprogramming(OOP)treatsaprogramasacollectionofobjectsthatinteractbymeansofactions.
OOPTerminologyObjects,appropriately,arecalledobjects.Actions arecalledmethods.Objectsofthesamekindhavethesametype andbelongtothesameclass.◦ Objectswithinaclasshaveacommonsetofmethodsandthesamekindsofdata
◦ buteachobjectcanhaveit’sowndatavalues.
OOPDesignPrinciplesOOPadherestothreeprimarydesignprinciples:◦ Encapsulation◦ Polymorphism◦ Inheritance
IntroductiontoEncapsulationThedataandmethodsassociatedwithanyparticularclassareencapsulated(“puttogetherinacapsule”),butonlypartofthecontentsismadeaccessible.◦ Encapsulationprovidesameansofusingtheclass,butitomitsthedetailsofhowtheclassworks.
◦ Encapsulationofteniscalledinformationhiding.
ExampleAnautomobileconsistsofseveralpartsandpiecesandiscapableofdoingmanyusefulthings.◦ Awarenessoftheacceleratorpedal,thebrakepedal,andthesteeringwheelisimportanttothedriver.
◦ Awarenessofthefuelinjectors,theautomaticbrakingcontrolsystem,andthepowersteeringpumpisnotimportanttothedriver.
IntroductiontoInheritanceClassescanbeorganizedusinginheritance.
Aclassatlowerlevelsinheritsallthecharacteristicsofclassesaboveitinthehierarchy.
Ateachlevel,classificationsbecomemorespecializedbyaddingothercharacteristics.
Higherclassesaremoreinclusive;lowerclassesarelessinclusive.
IntroductiontoInheritance
VariablesVariables storedatasuchasnumbersandletters.◦ Thinkofthemasplacestostoredata.◦ Theyareimplementedasmemorylocations.
Thedatastoredbyavariableiscalleditsvalue.◦ Thevalueisstoredinthememorylocation.
Itsvaluecanbechanged.
NamingandDeclaringVariablesChoosenamesthatarehelpfulsuchascount orspeed,butnotc ors.
Whenyoudeclare avariable,youprovideitsnameandtype.
int heightInCentimeters,age;
Avariable'stype determineswhatkindsofvaluesitcanhold(int, double, char, etc.).
Avariablemustbedeclaredbeforeitisused.
DataTypesAclasstype isusedforaclassofobjectsandhasbothdataandmethods.◦ "Java is fun" isavalueofclasstypeString
Aprimitivetype isusedforsimple,nondecomposablevaluessuchasanindividualnumberorindividualcharacter.◦ int, double, andchar areprimitivetypes.
PrimitiveTypes
PrimitiveTypesFourintegertypes(byte, short, int, andlong)◦ int ismostcommon
Twofloating-pointtypes(float anddouble)◦ double ismorecommon
Onecharactertype(char)Onebooleantype(boolean)
ExamplesofPrimitiveValuesIntegertypes
0 -1 365 12000
Floating-pointtypes0.99 -22.8 3.14159 5.0
Charactertype'a' 'A' '#' ' '
Booleantypetrue false
AssignmentStatementsAnassignmentstatementisusedtoassignavaluetoavariable.answer = 42;
The"equalsign"iscalledtheassignmentoperator.Wesay,"Thevariablenamedanswer isassignedavalueof42,"ormoresimply,"answer isassigned42."
AssignmentExamplesamount = 3.99;
firstInitial = 'W';
birthYear = currentYear - age;
total = total + 2;
AssignmentCompatibilitiesJavaissaidtobestronglytyped.◦ Youcan't,forexample,assignafloatingpointvaluetoavariabledeclaredtostoreaninteger.
Sometimesconversionsbetweennumbersarepossible.doubleVariable = 7;
ispossibleevenifdoubleVariable isoftypedouble,forexample.
ArithmeticOperatorsArithmeticexpressionscanbeformedusingthe+, -, *, and/operatorstogetherwithvariablesornumbersreferredtoasoperands.◦ Whenbothoperandsareofthesametype,theresultisofthattype.◦ Whenoneoftheoperandsisafloating-pointtypeandtheotherisaninteger,theresultisafloatingpointtype.
ArithmeticOperatorsExample
IfhoursWorked isanint towhichthevalue40 hasbeenassigned,andpayRate isadouble towhich8.25 hasbeenassigned
hoursWorked * payRate
isadouble withavalueof500.0.
TheDivisionOperatorThedivisionoperator(/)behavesasexpectedifoneoftheoperandsisafloating-pointtype.Whenbothoperandsareintegertypes,theresultistruncated,notrounded.◦ Hence,99/100hasavalueof0.
Themod OperatorThemod (%)operatorisusedwithoperatorsofintegertypetoobtaintheremainderafterintegerdivision.14dividedby4is3witharemainderof2.◦ Hence,14 % 4 isequalto2.
Themodoperatorhasmanyuses,including◦ determiningifanintegerisoddoreven◦ determiningifoneintegerisevenlydivisiblebyanotherinteger.
SampleExpressions
TheClassStringWe'veusedconstantsoftypeString already."Enter a whole number from 1 to 99."
AvalueoftypeString isa◦ Sequenceofcharacters◦ Treatedasasingleitem.
ConcatenationofStringsTwostringsareconcatenated usingthe+ operator.String greeting = "Hello";String sentence;sentence = greeting + " madam";System.out.println(sentence);
Anynumberofstringscanbeconcatenatedusingthe+ operator.
ClassandMethodDefinitions
ClassandMethodDefinitions
Objects that are instantiations of the
class Automobile
MethodsWhenyouuseamethodyou"invoke"or"call"itTwokindsofJavamethods◦ Returnasingleitem◦ Performsomeotheraction– avoid method
Themethodmain isavoidmethod◦ Invokedbythesystem◦ Notbytheapplicationprogram