CS 10: Problem Solving Via Object Oriented Programming

Transcription

CS 10:Problem solving via Object OrientedProgrammingWelcome to the class!Class goal, syllabus, starting on OOP and Java

Today main learning goals1. Learn about each other2. Learn about CS10, outcomes, teachingmethods/tools, and expectations3. Learn about basic Java structure andmain elements of OOP2

Agenda1. You, the teaching team, and thiscourse2. Dive into Object OrientedProgramming (OOP)3

Your background How did you satisfy the pre-reqs? CS 1 ENGS 20 AP exam Other What’s your future plan? CS majors? Minors? Not sure? How many of you programmed in Java before?4

My background: roboticistB.Sc. in CS&Eng (2006-2009)Dartmouth Reality and Robotics Lab(2018-present)M.Sc. (2009-2011) and Ph.D.in CS&Eng (2012-2015)Taught coursesProblem Solving via Object OrientedProgramming (COSC10)Artificial Intelligence (COSC76/276)Postdoc/Research faculty(2015-2018)Principles of Robot Design and Programming(COSC81/181)Machine Learning for Robotics (COSC89/189)Multirobot Systems (COSC69/169)Robotics Perception Systems (COSC69/169)5

Teaching teamSayantonDibboCallieMoodyJuliaGottschalkXu TianChukwukaV. barakIdokoAneeshPatnaikDan haudharyAnnie QiuGraceWangIsabellaHochschildWill Perez6

Primary objective of the courseReinforce the foundational perspective and skills neededto develop computational solutions to real interesting problems.CS87/187 Rendering algorithmsCS83/183 Computer VisionCS81/181 RoboticsAnd many others, including Artificial intelligence, Machine learning,Bioinformatics, aduate-courses7

Main learning outcomes:Problem solving via Object Oriented ProgrammingProbleme.g., tputLearn by implementingand debugging!?Data structuresAlgorithms 8

Learning resources: multimodalLectures for covering concepts 12 time slot MWF 12:50-1:55 pm EDT (recordingposted afterwards)X Tu 1:20-2:10pm EDT (see on Canvas if used) Feel free to ask questionsRecitation section meetings for hands-on: 1 hour/week (starting this week)Website for notes, slides, and assignmentinstructions (https://www.cs.dartmouth.edu/cs10/) Syllabus ScheduleTextbook for additional examples and explanations: DataStructures & Algorithms in Java , 6th ed, by Goodrich, Tamassia,and Goldwasser10

Learning resources: assessmentTo assess your learning, you will:1. Solve recitation section meeting programmingdrills and short assignments by writing relativelysmall code snippets to consolidate the conceptslearned every week in class.2. Solve problem sets by writing programs to applythe concepts learned in class to real-worldproblems. You can find one problem set collaborator3. Answer exam questions.5%10%30%55%Please see the details on the syllabus (late policy,grade, extra credit, )https://www.cs.dartmouth.edu/cs10/#coursework8 recitation section meetingprogramming drills10 short assignments6 ProblemsetsExams: 2 midterms (each 15%) 1 cumulative final (25%)Please reach out if you’re falling behind – we’re happyto help11

Learning resources: how to get help Few channels to simplify the use (access viaCanvas) #classes-discussion: for questions and discussions on the concepts coveredin the class.#course-announcements: for general discussions and announcements.#help-assignments: for questions and discussions on the assignments.Help each other (please remember the honor code; if in doubt, ask) Don’t post solution!The teaching team will typically respond within 24 hours Use the public channels first Don’t hesitate to ping in case we missed your messageAnonymous messages are possible with /anon commandDirect messages instead of emailsLet’s build an inclusive community!Office hours ( 3 hours/week each member of theteaching team) Prof. and TAs Each of you will have a reference TA tohave a long-term support ECSC building Zoom to accommodate your preference12

Learning resources: other tools 755) Calendar with office hoursSection assignmentsLink to SlackLink to GradescopeLink to PanoptoRecord of assignment and currentoverall gradingRecordings on Panopto folder (access through Canvas)Submissions via Gradescope (access through Canvas) forconsistent gradingIf you have any problem, please let me know13

Tentative schedulePlease keep an eye as everything will be posted edu/cs10/schedule.html14

Short Assignment (SA-0) out, completesurvey before x-hour Find it on Gradescope (via Canvas)Take course survey to understand your background and assignyou to a sectionSet up development environment (IntelliJ IDEA) and get HelloWorld running Instructions and screen shots provided on Create your first Java classRead and acknowledge course policies and honor code If you have any questions or comments, please feel free to leave acommentComplete survey before 8:00am tomorrow (or risk gettingassigned to inconvenient section time!)X-hour this week15

Learning resources: adviceSuccessful learning in the class is typically associated with Reading the material recommended Actively Participating in the class Starting all assignments as soon as they are out Reaching out for help immediately when stuckWe’re hopefully phase and we will succeed if we worktogether Please talk to us if you are running behind or if youhave any questions/comments16

Agenda1. You, me, and this course2. Dive into Object OrientedProgramming (OOP)17

OOP four main pillars for robust, adaptableand reusable m18

Abstraction19

Encapsulation20

Inheritance21

Polymorphism22

OOP is popular, especially in largeorganizationsTop languages used in large organizations Each of themostcommonlanguages isobjectorientedJavaC C#Python0102030405060Percentage of organizations using language70 Java isparticularlypopular inlargeorganizations23Source: veloper-Language-Report FINAL.pdf (Javascript omitted)

Interpreted vs. compiled languageimport java.lang.*import java.lang.*--------------------import import ------------------------------------------------ ------Source Code---------------------- ------------------Print Hello Hello World!RunHigh Level Language code24

Interpreted vs. compiled languageimport java.lang.*import java.lang.*--------------------import import ------------------------------------------------ ------Source Code---------------------- ------------------Print Hello ---------------------------------------executable machine 1010RunHigh Level Language codeHello World!25

We can flesh out the boilerplate code toprint “Hello World!” to the consolePythonJava26

Today we will focus on encapsulation27

Problem: “blob” that will move around thescreenBlobs are graphical objects that move around the screenA glorious blobobjectWhat data andactions the blobwill have?28

Blob0.java: very simple classWhat do we expectthis program toprint?29

Blob01.java: setters30

Blob02.java: Constructors31

Blob02.java: ConstructorsWhat do we expectthis program toprint?32

Blob02: Constructors called when an objectis first instantiated (run before other code)Output appears in console33

Blob.java: Small changes to previousversions give a more full featured Blob34

Blob: Small changes to previous versionsgive a more full featured Blob35

Blob: Small changes to previous versionsgive a more full featured Blob36

Blob: New methods to control how theblob behavesWhat does thestep() function do?37

BlobDriver.java: Create a “driver” programseparate from class definitions38

BlobDriver: Uses Blob class to create blobobjects and then move/grow themOutput39

Some application examples for the blob?40

Summary Syllabus: active learning Object-oriented programming ancePolymorphism Java syntax and keywords: main, class, variable type, instancevariables Simple Java object (focus on encapsulation)–––––Logical code separation to improve reusabilitySetter, getterConstructorOverloadingDriver separate from class definitions41

Next Inheritance and polymorphism Event driven programming42

Additional Resources43

CREATING HELLO WORLD44

In keeping with tradition, we’ll start with“Hello world”HelloWorld.java1. Start IntelliJ, create “cs10” Java Project (only need to do this one time)2. Create “day1” Source folder to logically group your source code (e.g., “PS1” Source folderholds all the source code for Problem Set 1)3. Create new “HelloWorld” class in “day1” source folder File on disk is “HelloWorld.java” Class Name is “HelloWorld” IntelliJ “stubs” out “main” method (where program execution starts)Other items of note:Javadoc Java documentation feature Enter description for Class or method Starts with “/**”, ends with “*/” Can add tags such as “@author” or “@param”main() is where action startsAdd System.out.println(“Hello World”) to output to the consoleRight click on code and choose “Run class name .main()” button to run45

1. Create “cs10” Project to hold sourcecode (only need to do this one time)Start IntelliJ, then select “Create new project” or click File- New- Project1) ChooseJava2) ChooseJavaversion3) Takedefaults4) ClickNext46

1. Create “cs10” Project to hold sourcecode (only need to do this one time)Do not create project from template1) LeaveUNCHECKED2) Click Next47

1. Create “cs10” Project to hold sourcecode (only need to do this one time)Name project “cs10” and set directory on disk where code will be stored1) ChooseProject name(“cs10”)2) Choosedirectory wherecode will bestored3) Click Finish48

2. Create Source folder to hold your sourcecode for day one of classClick File- New- Directory to create directory for related code (e.g., “day1” or “PS1”)2) Give directory a name1) Click File- New- DirectorySource folders are a useful way toorganize your code (ex. PS1 Source foldercontains all code for Problem Set 1)3) Right clickon newdirectorythen select“MarkDirectoryas” and“SourcesRoot”49

3. Create new “HelloWorld” class in “day1”source folderRight click on Source folder and select New- Java Class2) Give class a name (starting with capital letter)3) IntelliJ creates file on disk (e.g.,“HelloWorld.java”) and sets up your new class1) Right click on Source folder (e.g. “day1”),then select New- Java Class50

IntelliJ creates HelloWorld.java“boilerplate” codeFile on disk is HelloWorld.javaClass is named HelloWorld51

We can flesh out the boilerplate code toprint “Hello World!” to the consoleExecution begins at main() methodType “main” then enter and IntelliJ expands to include the main method declarationIn Java a print statement is System.out.println(“text you want to print goes here”);Type “sout” then enter to have IntelliJ fill out print statement for you (saves a lot of typing!)52

We can flesh out the boilerplate code toprint “Hello World!” to the consoleJavadoc Describes program (or method) Begins with “/**” ends with “*/”Add tags such as“@author” or “@param”53

Running the program prints “Hello World!”to consoleRun program by right clickingon program text and selecting“Run class name .main()”Output appears in console below54

Design of class for “blob”ANNOTATED SLIDES55

We start with different types of “blob”objects that will move around the screenBlobs are graphical objects that move around the screenA glorious blobobject Each blob encapsulates data it knows andcode it can execute into a single entity: Data: x,y location and radius Code: move, teleport, etc There will eventually be many types of blobsthat behave differently Each type of blob will inherit behavior from abase class We will model blobs as objects Objects encapsulate: Data they know (e.g., x,ylocation and radius) Actions they can take (e.g,move, teleport) called methods Objects are defined by a class Like a blueprint – a class tellshow to create an object (suchas a house) Does not itself create objects Each object is instantiated (created)from the class in Java using the“new” keyword There can be many objects createdfrom the same class (like there canbe many houses built from the same56blueprint)

Blob0.javaANNOTATED SLIDES57

Blob0.java58

Blob0: Our first “real” class uses instancevariables to store data about objectsClass Blob0 holds data about anobject’s position on the screen(x, y coordinates) and object’sradius (size) in “instance”variables59

Blob0: Our first “real” class uses instancevariables to store data about objectsInstance variables Track blob’s location and size Must declare type (double is anumeric value that has adecimal part) Java initializes to 0 (or false ornull) by default Each object we create gets itsown instance variables60

Blob0: Our first “real” class uses instancevariables to store data about objects “Instance” of class Blob0 called“bob” is “instantiated”(created) bob’s type is Blob0, akin tohow x is a double Use keyword “new” to create anew object of type Blob0 Java initializes instancevariables x, y, and r to 061

Blob0: Our first “real” class uses instancevariables to store data about objects Location of “bob theBlob” is printed toconsole x and y are updated(like in Python) New location is printed62

Blob0: Our first “real” class uses instancevariables to store data about objectsWhen run, output appears in console63

Blob0: Directly updating instance variablesis bad form – we can do better! Updating instance variablesdirectly is considered bad formin Java (but not in Python) We will not do this in Java! Better to let the objects updateown instance variables64

Blob01.javaANNOTATED SLIDES65

Blob01: Declaring instance variables as“protected” prevents outside modification “Protected” allows this class(and subclasses) to accessinstance variables Others cannot More on this later66

Blob01: Add a “setter” method to allow theobject to update its own instance variables “Setter” method allowsobject to update its owninstance variables based onvalue passed in Could do error checking here(ex., suppose x can’t benegative) Note the one line syntax!67

Blob01: Add a “setter” method to allow theobject to update its own instance variables “this.x” means the “instancevariable x” for this object x refers to the parameter “this” is like “self” in Python“Getter” methods return the value of instance variables (see Blob.java)68

Blob01: Add a “setter” method to allow theobject to update its own instance variablesInstance variable x now updatedthough setter method, ratherthan accessed directly like Blob069

Blob01: Javadoc allows you to documentyour methods JavaDoc describes what thismethod does and whatparameters it takes Get used to writing these!70

Blob02.javaANNOTATED SLIDES71

Blob02.java72

Blob02: Instance variables can be initializedto values other than zero r is initialized to 5 for all newobjects x and y initialized to zero73

Blob02: Constructors called when an objectis first instantiated (run before other code) Constructors have same name as classCalled when object is first instantiatedThis constructor takes no parametersx,y instance variables initialized to 0If you don’t provide any constructors,then you implicitly get one like this74

Blob02: Constructors called when an objectis first instantiated (run before other code)Why do we use “this”here? This constructor takestwo parameters, one forx, and one for y Multiple methods withsame name is calledoverloading Java determines whichto use based onparameters providedwhen called What value does r get?75

Blob02: Constructors called when an objectis first instantiated (run before other code) In main() we create twoobjects: bob and alice Each calls a differentconstructor Each object’s instancevariables are initializedto different values (e.g.,bob and alice havedifferent x and y values)76

Blob02: Constructors called when an objectis first instantiated (run before other code)Output appears in console77

Blob.javaANNOTATED SLIDES78

Blob.java79

Blob: Small changes to previous versionsgive a more full featured BlobNew instance variables dx,dy,dr will be the amount eachinstance variable changes at eachtime step80

Blob: Small changes to previous versionsgive a more full featured BlobThree (overloaded) constructors Like previous constructors Now allow for 0, 2, or 3parameters81

Blob: Small changes to previous versionsgive a more full featured BlobReturn type, onlyone return valueVoid meansreturns nothingGetters and setters for eachinstance variable Nothing special about the namesgetY, setY to get/set Y We use get Variable name byconvention Could use another name to get orset Y, but other programmers willlook for getter/setter in this format(but Java doesn’t care what we call82them)

Blob: Small changes to previous versionsgive a more full featured BlobsetVelocity() sets dx and dyCan update multiple variables inone call if you want, but you’d alsonormally have a setDX and getDXsetGrowth() sets drThis is ok, but doesn’t follow Java’stypical naming convention83

Blob: New methods to control how theblob behavesstep() Updates x, y, and r by dx, dy,and dr Will soon be called eachtime a clock “ticks” Note: dx, dy, and dr can benegative! That could cause problemsdepending on use case (hereit does not)84

Blob: New methods to control how theblob behavescontains(x2,y2) Checks to see if a point at x2, y2is inside the blob’s radius Returns true if point iscontained, otherwise, falseThree types of variablespresent in contains(): Parameters (x2,y2) Instance variables (x,y,r) Local variables (dx,dy) Local variables “hide”instance variables here! draw() function displays blob on screen More on that later85

BlobDriver.javaANNOTATED SLIDES86

BlobDriver.java: Create a “driver” programseparate from class definitions87

BlobDriver: Uses Blob class to create blobobjects and then move/grow themBlobDriver class infile BlobDriver.javaUses class Blob defined in fileBlob.javaReference to Blob allowed if classesdefined in same project (cs10 here)Key point: Blob class is not defined in the“driver” or “application” class BlobDriver,but BlobDriver can use the Blob code if it isin the same project88

BlobDriver: Uses Blob class to create blobobjects and then move/grow themCreate bob and aliceobjects from class Blobbob: x 10, y 20, r 5alice: x 30, y 40, r 5Set bob.r 2*alice.r 2*5 10Set alice.dx 3, dy 4Set bob.dr 1089

BlobDriver: Uses Blob class to create blobobjects and then move/grow themstep() adds dx, dy, and dr to x, y, and rPrint bob and alicelocations to console90

BlobDriver: Uses Blob class to create blobobjects and then move/grow themOutput91

OOP, not simply how to program in Java Focus will be on solving problems with Object Oriented Programming (OOP), and you’ll learn some Java along the way OOP is not the only way to solve problems, but it can be useful The course has three main components that overlap somewhat: 1.Obje