Compsc sci 201 201 Classe sses, s, Arrays, s, A APIs State Constructor Susan Rodger January 17, 2020 Methods (behavior) 1/17/2020 Compsci 201, Spring 2020 1
Be in the know … • Add yourself elf t to compsci@ ci@duk uke.edu • Duke University mailing lists – add yourself https://lists.duke.edu/sympa • Compsci related events, jobs, research opportunities • Appl Apply fo for Dat ata+, CS+, Code+ e+ • summer research at Duke, paid, hire lots of 1 st year students, 2cd year, etc. • Apply in January! https://www.cs.duke.edu/undergrad/summer_research 1/17/2020 Compsci 201, Spring 2020 2
C is for … • Class • Framework for creating objects • Collections and Collection • See java.util.* for details • Collaboration • Review the policy 1/17/2020 Compsci 201, Spring 2020 3
Plan for the Day • Revie iew Obj bject t concept: t: c classes, P P0 • What is a class, object, instance variable • Revie iew arrays in J Java: m meth thods ds and c d concepts ts • Required for APTs due next week • Move toward ArrayList and other collections • Codin ing a and h d helpe lper f functio tions • Efficient programming and not efficient programs 1/17/2020 Compsci 201, Spring 2020 4
Strings: Example from last time • You u can an’t m modif ify a a string, alw always crea eate ne new S String String s = new String(“joy"); String t = s; s = t + t; // contents of boxes the same 1/15/2020 Compsci 201, Spring 2020 5
Class • Adject ctiv ive, n noun, c n, close t to a verb • Show some ___ you're in a great ___, that's a ___ act, let's ___-ify that • Fundam ament ental p al part o of object ct-ori riented p pro rogra grammi mming • All Java code is in a class, alas the primitives • In Python int is a class, has no upper bound • In Java int is a primitive, 2 31 -1 maximal value 1/17/2020 Compsci 201, Spring 2020 9
Class encapsulates state and behavior • Class i is a templa late, o , object ect h has c char aract cter eris istics ics • Dogs have fur, speed, temperament, size, … • Typic icall lly w we e don’t us use ex exam amples lik like t thi his, b but ut t the hey can an help help b build uild int intuition and and und understanding • Class dog, retriever extends dog, method bark() 1/17/2020 Compsci 201, Spring 2020 10
Class and Object • If w we e had had a R a Retriever class we c e coul uld instant ntia iate a an instance nce o of the c e class, i. , i.e., ., c create a e an o object ct Retriever ks = new Retriever("kelsey"); • Cla lass is is an an object f t factory , c , calling ling new create tes a s a ne new o objec ect t tha hat is is an an ins instance o of the he c cla lass • We could call a method: ks.bark() 1/17/2020 Compsci 201, Spring 2020 11
Classes in Java • Define class Foo in Foo.java State • Create object by calling Constructor new Foo(..) • Access object by calling Methods methods: (behavior) obj.doSomething() • Some methods return a value, use it! 1/17/2020 Compsci 201, Spring 2020 12
Classes in Java • State: instance variables: private • Constru ructors rs: initialize instance variables • Met etho hods: functions aka behavior • Docum ument entatio ion: Javadoc and other comments 1/17/2020 Compsci 201, Spring 2020 13
Work-Flow for Assignments • Wha hat is is the he work-flo low f for P0 and A Assig ignm nment nts? • Login to gitlab • Code URL to P0 in gitlab • Fork it (makes a copy in the cloud) • Clone with ssh 1/17/2020 Compsci 201, Spring 2020 15
Using a shell • Place t ace to type s shell c ell command nds • On n Mac ac us use T Ter erminal, W Wind indows us use B e Bash G Git it • Wha hat is is thi his? • It’s a a pat ath: h: • Folder named IdeaProjects • Folder named spring20 – May have other folders inside it • $ $ is is a p a prompt, rea eady for a s a shel hell co command 1/17/2020 Compsci 201, Spring 2020 16
A few shell commands • pw pwd – di displ play c current pa path • cd d – cha hang nge i e into m main f n folder er/dir irect ectory • cd nam name -- -- cha hange int into f fold lder nam named nam name • cd .. .. – cha hang nge e back i into p parent nt f folder • ls ls -- -- sho how f file iles in in cur current f fold lder • Let’s s see s some o of those… e…. 1/17/2020 Compsci 201, Spring 2020 18
Back to Work-Flow for Assignments • Clone ne wit ith h ssh sh • Go o to o you our s shell • cd (to folder you want to put your P0 in) • git clone (SSH URL you copied) • ls (will show your files) • Using ng I IntelliJ elliJ c comple lete t the as assig ignm nment nt • Save code often to gitlab! 1/17/2020 Compsci 201, Spring 2020 19
Work-Flow for Assignments (cont) • Send d code de b back k to to gitl itlab (DO O OFTEN) • cd ( into project folder) • git add . • Puts code in staging area, tells git you want to update • git commit –m “comment on what you did” • Changes are recorded in local repo • git push • Uploads the changes to your gitlab repo • No Now t w to Gradesc scop ope and s d submit bmit project ect • Don’t like results - fix code, push code, run on Gradescope again 1/17/2020 Compsci 201, Spring 2020 20
Classes and P0 • How many any P Per erson o objec ects c created? • Each has a name and an age, different for each instance. Thus: instance variables 1/17/2020 Compsci 201, Spring 2020 22
Classes and P0 • How many Person o objects cr created? • Each has a name and an age, different for each instance. Thus: instance variables • To cr create? Call ne new w whi hich inv nvokes a a co constructor • No return type, initialize instance variables • Acces ccess l level els: p private o e only w withi hin c n class, p public f c from other her c classes es • Technically there is a package access, we ignore 1/17/2020 Compsci 201, Spring 2020 23
1/17/2020 Compsci 201, Spring 2020 24
Constructor • Sam ame nam name a as c cla lass • No return type • Overlo load ad with d differ erent ent p parameters • Each should initialize all instance variables • Fac actor o out ut c common co code int into help helper m method if if leng lengthy • Can call another constructor using this(…) 1/17/2020 Compsci 201, Spring 2020 25
What is this ? • An object ct i instanc ance r ref efer ers t to itself elf • Method or constructor: object references itself • Every reference to an instance variable myVar could be written as this.myVar • Code f e for a an object ct t to pass i itself elf: • callMethod(this,"hello"); • Construct uctor c can c n call o ll other er construc uctor • this("hello"); 1/17/2020 Compsci 201, Spring 2020 26
Running a Java Program • On n lap laptop/desktop la laun unch/run p point int is is t the m he main ain method in in any any c cla lass • Driver programs in P0, runs/drives the code • Method signature requir uired to run program 1/17/2020 Compsci 201, Spring 2020 27
WOTO (3 minutes) http:// //bi bit.ly/2 /201spr pring20-01 0117 17-1 1/17/2020 Compsci 201, Spring 2020 28
Luis von Ahn Duke 2000, Math • Duke Honorary Degree 2017 • CEO Duolingo • Macarthur Award, 2006 • MIT-Lemelson Prize, 2018 • “It’s amazing how motivating it is to sit with somebody and say, ‘What you’re doing is really important.’ I use that a lot.” 1/17/2020 Compsci 201, Spring 2020 29
Arrays, APTs, and APIs • Why hy is is alli alliteration im important in in writ iting? • Why are t thes ese i e important nt i in program amming ing? • APIs c crea eate p e possib ibilit ilitie ies 1/17/2020 Compsci 201, Spring 2020 30
Array Details • Once a ce array c created, it' t's siz ize i e is fixed, c can' n't g grow! • Indexable elements can be changed • Using g a[k] we can r n read/w /writ ite va values ues • Instance variable a.length is size of array • No parentheses, hence not a method • Notice dot notation: object dot name 1/17/2020 Compsci 201, Spring 2020 31
Indexing for loops and arrays • Constr tructin ting and i d initi itiali lizing … … int[] a = new int[100]; for(int k=0; k < a.length; k += 1){ a[k] = 99; } • Let an A n API-call ll f fill i ll in array: y: java.util.Arrays • Arrays.fill(a,99); • https://docs.oracle.com/en/java/javase/11/docs/api/ java.base/java/util/Arrays.html Compsci 201, Spring 2020 32 1/17/2020
For each loops and arrays • For each l loop: no no ind ndex, no no cha changing w wha hat’s s stored int[] a = {1,2,3,4,5,6,7,8,9,10}; int sum1 = 0; int sum2 = 0; for(int k=0; k < a.length; k += 1){ sum1 += a[k]; } for(int value : a){ sum2 += value; } System.out.println(sum1 == sum2); 1/17/2020 Compsci 201, Spring 2020 33
Recommend
More recommend