Object Oriented Programming Lecture Notes

object oriented programming c++ lecture notes and lecture notes in c++ | pdf free download
ShawnPacinocal Profile Pic
ShawnPacinocal,United States,Researcher
Published Date:09-07-2017
Your Website URL(Optional)
1005ICT Object Oriented Programming Lecture Notes School of Information and Communication Technology Griffith University Semester 2, 2015 113 1 Introduction Welcome to 1005ICT object oriented programming (OOP). These lecture notes are divided into sections. This one describes the course’s: • content; • roles and responsibilities; • assessment; • resources; and • some things you need to do now. 1.1 7005ICT Programming Principles 2 For this semester, the class also includes Masters students enrolled in 7005ICT Program- ming Principles 2 (PP2). The course materials and assessment items will be the same as for the undergraduate course, however the grading basis will be different. Please note that this is the second part of our introduction to programming. If your undergraduate program did not include programming, please see the course convenor or your program convenor for advice as to whether this is the right course for you. 1.2 Take notes? These notes are posted on the web. So you don’t have to copy them all down. But we say more than goes in the slides. You should be prepared to take notes that capture the extra information. 1.2.1 Take notes today Write down the things in colour. 1.3 Course Convenors & Lecturers course convenor Andrew Rock & lecturer a.rockgriffith.edu.au Technology Building (N44) 1.37 1.4 Course web site These notes will be posted on the web at: http://www.ict.griffith.edu.au/arock/oop/ You will find the laboratory notes and anything else you need there too. Write down the uniform resource locator (URL) now14 1 INTRODUCTION You can also access these resources via LearningGriffith, though direct access via the above URL will be quicker. Lectures are captured and available, after editing, on LearningGriffith’s Echocentre. 1.5 What the course is about This is the second part of an introduction to: • programming tools; • programming concepts; • problem solving; and • programming languages. The emphasis will be on the object oriented aspects of the Java programming language. 1.6 The choice of programming languages In your working life you will write lots of programs, in lots of programming languages. Any time you create a script, automation, spreadsheet, or animation, it’s programming. It may be that you never program in Java after completion of your programming classes. However, Java is a programming language that has all of the attributes found in all of the common application and scripting languages. Its notation is similar to many, including C, C++, C, JavaScript, and ActionScript. 1.7 Prerequisites This course assumes some knowledge of programming in an imperative programming language. Most of you will have completed 1001ICT Introduction To Programming (ITP). That course uses an imperative subset of Java, Making Stuff Happen (MaSH). If you have not done that particular course, any prior course on programming should provide an equivalent background. MaSH is very similar to C, Pascal, and related languages. If you do not have a pass or better for 1001ICT or an equivalent course, you are not qualified to undertake this course. See me asap, if you are unsure that you have the prerequisites. 1001ICT and 7001ICT are also offered this semester. 1.8 Classes and assessment 1.8.1 Lectures In a 2-hour lecture every week, we will learn the concepts and strategies used in program- ming. During 5 of the lectures, we will test your learning with quizzes. 3+4+5+6+7=25marks1.8 Classes and assessment 15 1.8.2 Workshops In a 1-hour workshop every week we demonstrate more examples and provide and discuss extra non-assessed problems. 1.8.3 Labs In 10 2-hour assessed lab classes you put the theory into practice. 2+2+3+3+4+4+5+5+6+6=40marks 1.8.4 Common times A common time is a class where there are no set activities, but you can get individual help if you need it or we can challenge you with extra, harder problems if you want them. 1.8.5 Final project The course ends with a larger programming project (35 marks). 1.8.6 Attendance summary Students are expected to attend all lectures and workshops. You are enrolled in one 2 hour labs class. Attend that every week from week 2. Attend any common time as needed, from week 2. “Eighty percent of success is showing up.” – Woody Allen. 1.8.7 Assessment summary quizzes 3+4+5+6+7= 25 labs 2+2+3+3+4+4+5+5+6+6= 40 project 35 total 100 1.8.8 Minimum requirements for labs and quizzes The labs are quizzes are treated as one assessment item each. If you do not attend the majority of each, we don’t think you are really attempting them. If you don’t attend at least 6 labs, you don’t get any lab marks at all. If you don’t attend at least 3 quizzes, you don’t get any quiz marks at all. Either of these outcomes will make it almost impossible to pass the course. You may even be awarded a grade of Fail Not Sat, which would be a better indication of your performance than a plain Fail.16 1 INTRODUCTION 1.8.9 Supplementary exam Supplementary assessment, if passed, can raise your grade from a 3 to the lowest passing grade (a 4). To be eligible, you must have been awarded a 3, have submitted/sat the majority of the assessed labs, the majority of the quizzes, and at least part of the final project. For this course, the supplementary assessment takes the form of a two-hour, closed- book, written examination. 1.9 Lecture notes The lecture notes are available on the course web site in various formats. The most useful format is the A5 version, which: • has a table of contents; • has an index; • has clickable links; • includes appendices that summarise the programming language and environments, plus other useful reference information; • is ideally formatted for a tablet or laptop screen; and • prints double-sided as a small book. 1.10 Griffith Sciences Laboratory Induction You will have been briefed in orientation about workplace health and safety, and the on- line course and test on LearningGriffith in the organisation Griffith Sciences Laboratory Induction that you must complete. In this course we will be checking that you have passed that test. You must print the certificate that shows that you passed that test, within the last year, and bring it to your first programming lab class (in week 2). 1.11 Peer Assisted Study Sessions At Nathan, this course has a student learning support service, Peer Assisted Study Ses- sions (PASS). PASS offers free extra weekly study sessions, led by more experienced fellow students (PASS leaders). The details about PASS will be presented by the PASS leaders in the week 2 lecture. PASS is optional (and limited access), but students who use it have been shown to get better results than students who don’t. At Logan PASS is not available. However, we are trying to find an alternate means of extra support, and change the Nathan PASS timetable so it is possible for Logan students to commute.1.12 Revision 17 Please use PASS or the alternatives Attendance is counted and if it drops below a certain level they get withdrawn. Just go to be social, so they are there when you need them. Don’t forget that they are led by high-achieving students, and they may have tips for you beyond the course content. 1.12 Revision There is no section in these lecture notes, marked “revision”. That would be boring to write, boring for students who had passed 1001ICT, and a bit mystifying for students with other backgrounds. All students should do some revision with their previous course materials. If you did 1001ICT, the last section Why MaSH Is Rubbish is a good place to start. As we walk through the new material, I will endeavour to indicate what is similar to what you have seen before and what is truly new. 1.13 Section summary This section covered: • why this course on programming is an important part of your program of studies; • prerequisites; • how this course is organised, taught and assessed; • where the resources for this course can be found on the web; • who the teachers are and how to contact them; and • what you need to do to get started in this course. 1.14 End of section feedback questions Send us your answers to these questions any time you like by clicking on them. • What was the most useful topic in this section? • What was the least useful topic in this section? • What was the least clear topic in this section? • What topic in this section would you like to like to know more about? • Did you find an error in this section?18 1 INTRODUCTION 1.15 Things to do What you need to be doing as soon as possible to get started: • Get a diary or organiser and plan how you can spend your week profitably, including the following items. • Make sure you are properly enrolled in this course and in a laboratory. • Read the course outline and the course web site. • Prepare for the first workshop by reading the exercises on the web site. • Prepare for laboratory 1, in week 2. Find the notes on the web site. There are some questions you need to answer before your lab class. • Complete the Griffith Sciences Laboratory Induction on LearningGriffith, and bring the printed certificate to labs at least once. • Revise your previous programming course notes. • Lecture notes appendices A and B contain useful information that you should read now.19 2 Kick-start Java This section provides just enough Java to enable the practical activities in the first labora- tory class (in week 2). The goals of the first laboratory will be to ensure that everyone (no matter their previous background) can edit and run a Java program using the most basic tools. The emphasis in this section is on how to do some basic things, but not on why we do them that way. 2.1 Hello, World This was the first and last example program in 1001ICT: public class Hello public static void main(String args) System.out.println("Hello, World"); It must be saved in a file calledHello.java. All of its components will be discussed below. 2.1.1 System.out.println() Use the procedure System.out.println() to print one anything – one String, oneint, oneboolean, etc. – and then a newline. Examples: System.out.println("Hello, World"); // String System.out.println(42); // int System.out.println(true); // boolean System.out.println(4.2); // double System.out.println("Meaning = " + 42); // What type? There is alsoSystem.out.print(), which does not output a newline. 2.1.2 The class The whole program is encapsulated in a class: public class Hello 20 2 KICK-START JAVA A class is the compilation unit for Java, that is, the smallest language element that the compiler will accept. normalClassDeclaration class identifier classBody classModifier (This is a syntax diagram. See Appendix B for an explanation of the notation.) public is an optional class modifier, but usual for a class that is to be made available for use. classModifier public private static Not all of these modifiers are useable with all kinds of classes. As we learn more about Java’s object oriented aspects, more modifiers will be introduced. The identifier is the name of the class. identifier javaLetter javaLetter digit not keyword booleanLiteral A class’s name must start with a capital letter. The name of apublic class must match the name of the file.2.1 Hello, World 21 javaLetter a Java programs are written in Unicode, ... so the definition of what is a letter, for the purpose of creating identifiers, is z very broad. A Letters may be selected from other scripts, such as Greek, but done rarely. ... Underscores are used to separate words Z within a name all in capitals. Any other Unicode letter Don’t use dollar signs. They are only for machine-generated code. _ Digits are the decimal digits. digit 0 ... 9 Theboolean literals arefalse andtrue. booleanLiteral false true All of Java’s keywords are listed below. keyword See list.22 2 KICK-START JAVA abstract double int strictfp assert else interface super boolean enum long switch break extends native synchronized byte final new this case finally null throw catch float package throws char for private transient class goto protected try const if public void continue implements return volatile default import short while do instanceof static The class body uses braces to encapsulate the sequence of class body declarations. classBody classBodyDeclaration In our example, there is only one declaration in the body, themain method. 2.1.3 The main method In general, a method is declared like this, with a header and a body. methodDeclaration methodHeader methodBody The header declares the interface by which this method may be called. methodHeader resultType methodDeclarator methodModifier methodDeclarator identifier ( ) formalParameterList The identifier is the method’s name, which should start with a lower case letter. methodModifier The method modifierspublic andprivate control the visi- public bility of a method from other classes. private static makes the method static (not dynamic), that is, belong- ing to the class and not to objects created at run-time. static2.1 Hello, World 23 The result type is either: resultType • a type, the type that will be returned by this function; or type • void, making this method a procedure that does not re- void turn anything. The formal parameter list shows the types and names of the method’s parameters. formalParameterList lastFormalParameter formalParameter , formalParameter type variableDeclaratorId lastFormalParameter formalParameter variableDeclaratorId identifier Later we will introduce another more interesting option for the last formal parameter. The program starts executing (aside from some initialisations) at themain method of the class that is run. public static void main(String args) • It must have the namemain; • must bepublic so it is visible to be called to start the program; • must bestatic so that it exists before any (dynamic) objects are created; • must be a procedure (“returns”void); and • must have a parameter with type array of strings. 2.1.4 Compiling The simplest way to compile the program is to invoke the Java compiler directly from the command line: javac Hello.java 24 2 KICK-START JAVA Where: • javac is the name of the Java compiler; and • Hello.java is the name of the Java source code file. • Hello.class is the object code file output by the compiler. It contains Java bytecode. 2.1.5 Running The simplest way to run the program is to invoke the Java virtual machine (JVM) directly from the command line: java Hello Hello, World Where: • java is the name of the JVM; and • Hello is the name of the class to run. 2.2 Hello, You Hello.java shows how to package a program and how to print something. Printing in Java is as easy as it is in MaSH, albeit a little more verbose. Reading is a bit trickier, and we’ll leave it for a bit. However the command line arguments make it easy to get a small amount of information into a program without reading. public class HelloYou public static void main(String args) System.out.println("Hello, " + args0 + ""); javac HelloYou.java java HelloYou Andrew Hello, Andrew The array of strings argument tomain holds any other command line arguments received by thejava command other than the class name.2.3 Add 25 2.3 Add We can input numbers this way, we just need to convert them from the strings. public class Add public static void main(String args) int a = Integer.parseInt(args0), b = Integer.parseInt(args1); System.out.println(a + " + " + b + " = " + (a + b)); javac Add.java java Add 1 2 1 + 2 = 3 The functionInteger.parseInt(String) converts a string to theint that it rep- resents. SimilarlyDouble.parseDouble(String)... Now we can write simple programs that print stuff with string or numeric inputs. 2.4 Section summary This section covered: • how to write a class; • how to write amain method; • how to print; • how to use command line arguments; • how to compile a program; and • how to run it. 2.5 End of section feedback questions Send us your answers to these questions any time you like by clicking on them. • What was the most useful topic in this section? • What was the least useful topic in this section?26 2 KICK-START JAVA • What was the least clear topic in this section? • What topic in this section would you like to like to know more about? • Did you find an error in this section? 2.6 Self-practice exercises Do these in your own time to revise a little programming. 1. Write a Java program that inputs a person’s height and weight as command line arguments and prints their body mass index (BMI). 2. Extend your BMI calculation program so that after the BMI is calculated, it tells the user whether they are underweight, overweight or in the normal range) 3. Write a Java program that accepts two integers and prints all of the integers between and inclusive of those numbers.27 3 The Software Development Process This section looks at the overall life cycle of software and provides a context for the design and implementation phases that are the main concerns of this course. 3.1 The waterfall model Software has a life cycle. It is conceived, developed, used, discarded, and replaced. The life cycle is described in various ways, but one of the most popular is the waterfall model. This model divides the process into phases, analysis, design, implementation, integration and maintenance. In a well-run project, the step from one phase to the next is made only after verification or testing. Detection, of an error that requires reversion to a previous phase is expensive The earlier a defect is detected, the cheaper it is to fix. Analysis Verification Design Verification Implementation Testing Integration Testing Maintenance The waterfall model phase delivers description exit phase when analysis requirements finding out what the the specification has specification software is supposed to been verified by the do requestors as meeting their needs28 3 THE SOFTWARE DEVELOPMENT PROCESS phase delivers description exit phase when design design figuring out how the the design has been software will do it verified to match the specification implementation software com- coding in programming each component sepa- ponents languages, creation of rately passes tests other assets (graphics etc.) integration deployable bringing the com- passes tests of the software ponents together, whole system installing maintenance ongoing sup- small fixes in re- the software no longer port sponse to changing meets the current re- circumstances quirements without a major reconsideration that belongs to an ear- lier phase The phase that lasts the longest (for a successful software project) is the maintenance, and it is therefore the most expensive over time. Maintenance will be cheaper and easier if the earlier phases are done better. 3.2 Other models There are plenty of other models for the software lifecycle and the development process. For example: iterative development, and agile development... All of these are just vari- ations on the waterfall model, with more willingness to accept that the looping back to pervious phases is inevitable in practice. So progress to later phases is not held up until the prior phases are 100% complete. 3.3 Human communication A large software project may divide these phases between different people or teams of people. It is almost guaranteed that the people performing the maintenance will not have been involved in the initial development. The success of the project depends as much on the communication between all these people as on the technical aspects. This course has an emphasis on the technical literacy required: reading and writing documentation, and design notation. 3.4 Use the right tools It is very important that the choice of the tools is made on the basis of the needs of the users and the project and not just the preferences or experience of the participants.3.5 Section summary 29 The law of the hammer: If you only have a hammer, everything looks like a nail. Good designs are language independent. A good object oriented design should be im- plementable in the best available object oriented programming language. The design notations should not be too specific to a particular language. 3.5 Section summary This section covered: • the waterfall model of the software development process and lifecycle; and • the need for language independence in design notations. 3.6 End of section feedback questions Send us your answers to these questions any time you like by clicking on them. • What was the most useful topic in this section? • What was the least useful topic in this section? • What was the least clear topic in this section? • What topic in this section would you like to like to know more about? • Did you find an error in this section?30 4 PROGRAMMING IN THE LARGE 4 Programming In the Large In this section we: • consider the levels of programming, programming-in-the-small versus programming- in-the-large; • introduce the Java application programming interface (API) and its documentation; and • introduce Java packages. Knowing how to read and use the Java API is as important as learning the Java language itself. 4.1 Small To large programs The assumed knowledge for this course is of programming-in-the-small. At the core of imperative/procedural programming are its five elements: assignment – variables, types, variable declarations, and assignment statements; calls – methods, procedures, functions, and calls to them; sequence – putting the above actions in a sequence to be carried out in order; iteration – loops, recursion, repetition of actions; and selection – choosing between alternate actions. With just these five elements, any program could be constructed. All of the generations of programming languages provide them. So why do modern programming languages provide a lot more features than just these? Two words: scale and cost. • Cost, because programmers want to get paid, and the people who hire them want to get the most value for that pay; and • scale, because real programs range from quite small to huge. A (crude) measure of how big a program is, is source lines of code (SLOC). Literally, how many lines of source code are used to create the program. Here are some SLOC figures quoted on the web (rarely published for closed-source programs): mashc 5 thousand Microsoft word (first version) 27 thousand Microsoft word (current) “at least a few million” World of Warcraft 5.5 million Windows XP 45 million Mac OS X 10.4 86 million4.2 The standard Java API 31 Only one of these examples was written by just one person. Most of these lines of code, are the kinds of lines you already know how to write, but there are a lot of them. Not only do all of these lines of code have to be written in the first place, they must: • be organised so that multiple people can find and access the parts of the code that they need to; • be organised so that multiple people can not destructively interfere with each other’s code; • be organised and documented so that they can be easily used and reused; and • be organised so that they can be maintained (debugged, and modified over time). Maintenance over time can be the most expensive part of a software’s total life. A modern programming language must promote: • the efficiency with which individual programmers work; • the efficiency with which teams of programmers work; • the reusability of code; • the maintainability of code; and • the efficiency with which code from different organisations can be combined. 4.2 The standard Java API Java is designed for small and large programming projects and has all the modern fea- tures to support programming in the large. The best place to see this demonstrated is by looking at the standard Java API. This is the most important reference source for Java programmers. It documents the pre-existing reusable code that they use to build new applications. 4.2.1 Where to find the Java API documentation Java was originally developed by computer scientists working for Sun Microsystems, which has since been taken over by Oracle. Hence: http://www.oracle.com/technetwork/java/ is the current start point for downloading Java tools and documentation. We will be using the Java Platform, Standard Edition (Java SE), at: http://www.oracle.com/technetwork/java/javase/