ebook img

Concise Guide to Object-Oriented Programming - An Accessible Approach Using Java. PDF

204 Pages·2019·6.31 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Concise Guide to Object-Oriented Programming - An Accessible Approach Using Java.

Undergraduate Topics in Computer Science Kingsley Sage Concise Guide to Object-Oriented Programming An Accessible Approach Using Java Undergraduate Topics in Computer Science Series Editor Ian Mackie, University of Sussex, Brighton, UK Advisory Editors Samson Abramsky, Department of Computer Science, University of Oxford, Oxford, UK Chris Hankin, Department of Computing, Imperial College London, London, UK Dexter C. Kozen, Computer Science Department, Cornell University, Ithaca, NY, USA Andrew Pitts, William Gates Building, University of Cambridge, Cambridge, UK Hanne Riis Nielson, Department of Applied Math and Computer Science, Technical University of Denmark, Kgs. Lyngby, Denmark StevenS.Skiena,DepartmentofComputerScience,StonyBrookUniversity,Stony Brook, NY, USA Iain Stewart, Department of Computer Science, Science Labs, University of Durham, Durham, UK Mike Hinchey, Lero, Tierney Building, University of Limerick, Limerick, Ireland ‘Undergraduate Topics in Computer Science’ (UTiCS) delivers high-quality instructional content for undergraduates studying in all areas of computing and information science. From core foundational and theoretical material to final-year topics and applications, UTiCS books take a fresh, concise, and modern approach and are ideal for self-study or for a one- or two-semester course. The texts are all authoredbyestablishedexpertsintheirfields,reviewedbyaninternationaladvisory board,andcontainnumerousexamplesandproblems,manyofwhichincludefully worked solutions. TheUTiCSconceptreliesonhigh-quality,concisebooksinsoftbackformat,and generallyamaximumof275-300pages.Forundergraduatetextbooksthatarelikely tobelonger,moreexpository,SpringercontinuestoofferthehighlyregardedTexts in Computer Science series, to which we refer potential authors. More information about this series at http://www.springer.com/series/7592 Kingsley Sage Concise Guide to Object-Oriented Programming An Accessible Approach Using Java 123 KingsleySage Schoolof Engineering andInformatics University of Sussex Falmer, EastSussex, UK ISSN 1863-7310 ISSN 2197-1781 (electronic) Undergraduate Topics inComputer Science ISBN978-3-030-13303-0 ISBN978-3-030-13304-7 (eBook) https://doi.org/10.1007/978-3-030-13304-7 LibraryofCongressControlNumber:2019931822 ©SpringerNatureSwitzerlandAG2019 Thisworkissubjecttocopyright.AllrightsarereservedbythePublisher,whetherthewholeorpart of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission orinformationstorageandretrieval,electronicadaptation,computersoftware,orbysimilarordissimilar methodologynowknownorhereafterdeveloped. The use of general descriptive names, registered names, trademarks, service marks, etc. in this publicationdoesnotimply,evenintheabsenceofaspecificstatement,thatsuchnamesareexemptfrom therelevantprotectivelawsandregulationsandthereforefreeforgeneraluse. The publisher, the authors and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, expressed or implied, with respect to the material contained hereinorforanyerrorsoromissionsthatmayhavebeenmade.Thepublisherremainsneutralwithregard tojurisdictionalclaimsinpublishedmapsandinstitutionalaffiliations. ThisSpringerimprintispublishedbytheregisteredcompanySpringerNatureSwitzerlandAG Theregisteredcompanyaddressis:Gewerbestrasse11,6330Cham,Switzerland Preface The twenty-first century continues to experience the relentless expansion of the IT revolution into our daily lives. We consume services, do our shopping on-line, listen to music streams and watch movies on demand. The impact of social media has had a profound impact on our society and has changed fundamentally theway we obtain and consume news, information and ideas. There is little sign of a slowdown in this dramatic shift in our relationship with technology. Vast research budgets are being applied to the development of autonomous vehicles, and in applying Artificial Intelligence to change the way we live. But it has also changed the demand for skills within our workforce. The demand for manual skills is in decline, and the demand for IT and programming skills is rising at an unprece- dented rate. Incomparison totheindustrialists ofthenineteenth andtwentiethcenturies, the twenty-first-centuryentrepreneursareexpertsinIT,programming, softwaredesign and development, and developing practical applications using concepts such as Artificial Intelligence for our daily lives. With this profound paradigm shift has come a need for the workforce of many industrialised nations to evolve. Govern- ments recognise the need for a huge increase in the workforce with programming skills.IntheUnitedKingdom,andinmanyotherindustrialisednations,corecoding skillsarenowapartofthesecondaryschoolcurriculum.Learningtoprogramisno longer considered to be just a part of the traditional journey of the Computer Science undergraduate, but a broader skill that underpins an IT literate workforce for the modern age. What is the Purpose of This Book? When I was first approached to write this book, it was suggested that its purpose was to provide an accessible introduction to coding and the world of Object Ori- ented Programming (OOP). Standard texts on the subject often fall between those that provide only a very lightweight treatment of the subject (“a little knowledge canbeafrustratingthing”),andthosethatrunto500pagesormorethatarerather better suited as referencetextsoras supporton a lengthy period ofstudy indepth. Thechallengeforthisbookistoprovideanaccessibleintroductiontotheworldof v vi Preface coding andOOP ina waythat ishelpful tothe first-time coderandallows themto develop and to understand their knowledge and skillsin a way that is relevant and practical. The examples developed for this book are intended to show how OOP skills can be used to create applications and programs that have everyday value, ratherthanexamplesthathavebeensynthesisedsolelytodemonstrateanacademic point. The reader should be able to use this book to develop a solid appreciation of OOP and how to code. The programming language used throughout is Java. Java has been chosen as it can be used across all computing platforms, because it has a commercialskillthathasaclearon-goingvaluederivedfromitsadoptionasacore languageforsmartphoneapplicationsontheAndroidplatform,andasthelanguage attheheartoftheJavaEE8JakartaEnterprisescaleframework.Thebookfocusses on the core Java language and does not consider smartphone or EE 8 coding, as theserequireskillsoverandabovewhatthisbookisabout.However,aknowledge ofcoreJavacodingandsomeoftherelatedissuesalsodiscussedinthisbookwould form an appropriate pre-requisite for the further study of these topics. Although this book uses Java as its illustrative programming language, many of the ideas may be translated directly into other OO languages such as C++, C# and others. Throughout this book, programming in Java is demonstrated using the BlueJIntegratedDevelopmentEnvironment(IDE).BlueJisawell-establishedIDE for learning BlueJ and is widely used in schools and Universities. Eclipse is the closest product to an industry standard for the development of Java, but it is often found too complex for the task of teaching and learning. Who is This Book Aimed at? As someone with over 20 years of teaching experience from level 3 through to postgraduate, from traditional University teaching to adult education, I have never beenabletoidentifysatisfactorilywhatdefinestheabilityofanindividualtolearn to program. Suffice to say, all that is really needed is an interest in the subject and time.TheaimofthisbookistoprovideanaccessibleentryintotheworldofObject Oriented Programming (OOP). The book does not assume any prior knowledge of coding, or any prior knowledgeofsoftwareengineeringorOO,notdoesitrequireanypriorexposureto mathematics. Whilst such prior knowledge is not unhelpful, it is not essential to learn to program. Instead, this book takes a more everyday experience to the subject,drawingonexamplesfromeverydayexperiencetoexplainwhatOOisand why it is relevant in the modern programming experience. As such, the book is aimedatthosewhoarecomingtoOOprogrammingforthefirsttime.Itistherefore likelytobeusefulasaone-semesterbookintroducingthetopictothosenewtothe study of computer science at the undergraduate and postgraduate levels, and those who are just learning for the purpose of self-improvement or professional devel- opment.Whilstthebookisaimedatthosewithnopriorcodingexperience,itdoes Preface vii explore broader topics surrounding coding. This with some prior knowledge may opt to skip some of the early chapters. That does not impact the usefulness of this book in terms of learning to code in Java. What’s in the Book? Chapter 1 starts with anoverview ofwhatprogrammingandcoding isallabout.It includes some useful historical perspective on the development of programming languages and the core ideas that underpin all programming languages. It intro- duces the idea of a computing machine and concepts such as a compiler. This section is helpful to those who have no prior experience of computing as it helps subsequent understanding of some of the core coding processes and terminology. The chapter then continues to discuss how the need for OOP arose in the period from the end of the 1970s to the present day, and a discussion of why it is considered important to help us solve modern-day programming problems. Chapter2providesashortintroductiontoprogramminginJavausingBlueJ.Itis intended to provide just enough knowledge and skills to create and execute a single-class Java program under BlueJ. This is significant as it then facilitates discussionofthecoreprinciplesofproceduralandstructuredprogramming,suchas loops and conditional statements. Those with prior experience of coding using languages such as C and Python may opt to skip this chapter, as they would undoubtedlybefamiliarwithmuchofthecontent.Ichosetoorganisethebookthis way as the basic procedural and structured coding constructions are common to almostallprogramming(oratleastthosethatowetheirsyntacticancestrytoC),and gettingtheseconstructionsunderstoodatthisstageallowsforamorespecificfocus later on the principles of OO. Chapter3getsintothedetailsofwhatOOreallyisandhowitcanbeappliedto solve modern programming challenges. We start with a discussion of what classes andobjectsare,andhowtheconstructionandexecutionofanOOprogramparallels thewaythathumanorganisationssuchasalargeofficeoperate.Suchanalogiesare invaluableinappreciatingthetruebenefitsoftheOOparadigm.Inthischapter,we develop a set of small multi-class Java applications and consider the cornerstone issues in OO design of class cohesion and coupling. Chapter 4 considers a range of Java library objects and packages such as the String and the ArrayList, and introduces the idea of the Application Pro- gramming Interface (API). This enables the reader to start building more complex applications involving simple linear collections of objects. These ideas are devel- opedusingasetofsimpleprogramsthatcanbeenhancedinmanydifferentwaysas an exercise for the reader. Chapter 5 delves further into the OO paradigm and considers how OO design forms an essential part of producing a useful solution to a problem. The chapter introducestheideaofclasspolymorphism(superandsub-classes)andhowthiscan beusedtocreateaprogramwithastructurethatmorecloselymirrorsanunderlying viii Preface domain. The chapter also looks further into the idea of selecting classes that are suitedtosolvingspecificproblemandsoalsohaselementsofsoftwareengineering principles and practice. Chapter 6 considers what to do when code encounters an error condition. Software systems are not immune to errors either at the coding or at the run time phases, and modern software systems need to be built in a robust manner so that they behave in a predictable manner when something goes wrong. The exception handling mechanism is introduced, along with steps on laying out a program to assist in debugging it. This chapter also considers practical measures that are adopted in defensive coding. Chapter 7 digs deeper into the work of arrays and collections, notably fixed length arrays, the HashMap and HashSet, and shows how different collection typescanbeusedtoeffectivelymodeldifferentreal-worldcollectionsofdata.This chapteralsoincludessomebackgroundontheunderlyingideasforthesecollection types, such as the hash table. Chapter 8 provides an introduction to building a Graphical User Interface (GUI)usingSwing.AlthoughsomemayconsiderSwingarelativelyoldlibraryfor the development of a GUI, the key ideas are relevant across a range of other libraries such as JavaFX, and Swing forms more of a core element of the Java landscape.ThedevelopmentofGUIsisalargetopicinitsownright,sothischapter canonlyeverserveasanintroduction.Inthischapter,wealsoconsidertheconcept of a design pattern, specifically the idea of Model View Controller (MVC) archi- tecture,andhowaJavaapplicationcanbeconstructedinawell-recognisabledesign configuration. In the final Chap. 9, two complete applications are presented, from conceptual design to implementation to help cement the ideas presented in the previous chapters. One is a text-based application with no Graphical User Interface (GUI). TheotherisasmallGUI-basedapplicationtogiveasenseofhowtobuildaGUIon top of an underlying application. Allthecodeexamplesusedinthisbookandthetwoexampleprojectsdescribed in Chap. 9 are available as on-line resource accompanying this book. Itismyhopethatthisbookwillinspirethereadertolearnmoreabouttheworld ofOOandcoding.Assuch,itrepresentsthestartofalearningjourney.Aswithall endeavours, clarity will improve with time and effort. Few will write an award-winning book at their first attempt. Few artists will paint their defining masterpiece at the outset of their career. Programming is no exception and your skills will improve with effort, time, reflection and experience. But every learning journeyhastostartsomewhere.Formany,thestorystartswiththecodebreakersof BletchleyParkintheUnitedKingdomduringWWII,butweshallstartourstoryin early nineteenth-century France … Falmer, UK Kingsley Sage January 2019 Contents 1 The Origins of Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 The Stored Digital Program is not a New Idea. . . . . . . . . . . . . . . 1 1.2 The Birth of the Computing Age. . . . . . . . . . . . . . . . . . . . . . . . . 3 1.3 The Origin of Programming Languages . . . . . . . . . . . . . . . . . . . . 4 1.4 The Object Oriented Revolution . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.5 The Java Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.6 Tools of the Trade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2 Procedural Programming Basics in Java . . . . . . . . . . . . . . . . . . . . . 11 2.1 First Program and Workflow. . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.3 The Procedural Programming Paradigm. . . . . . . . . . . . . . . . . . . . 19 2.4 Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 2.5 Alternation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 2.6 Repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2.7 More on Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 2.8 Bringing It All Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3 Getting into Object Oriented Programming . . . . . . . . . . . . . . . . . . . 37 3.1 Object Oriented in a Social Context. . . . . . . . . . . . . . . . . . . . . . . 37 3.2 Introducing the OO Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 3.3 The Anatomy of a Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 3.4 Creating Objects at Run Time. . . . . . . . . . . . . . . . . . . . . . . . . . . 47 3.5 Accessor and Mutator Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 52 3.6 Choosing the Right Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 4 Library Classes and Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.1 Organisation of Java into the Core and Packages . . . . . . . . . . . . . 57 4.2 Using Library Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 4.3 The String Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 4.4 Application Programming Interfaces (APIs) . . . . . . . . . . . . . . . . . 62 4.5 Using Javadocs in BlueJ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 ix

Description:
This engaging textbook provides an accessible introduction to coding and the world of Object-Oriented (OO) programming, using Java as the illustrative programming language. Emphasis is placed on what is most helpful for the first-time coder, in order to develop and understand their knowledge and ski
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.