Lecture 9 | Programming Methodology (Stanford)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this presentation is delivered by the Stanford center for professional development all righty welcome back wow that's pretty loud welcome back to a CS 106a I hope I didn't just shatter your eardrums and thanks for hanging it out in the rain I think the rain might have stopped a few people from making it today but actually today is one of the most important lectures of the whole quarter so it's too bad that it would happen to happen that way um so a couple quick announcements one is that there's two handouts one on coding style and one on the use of variables I'd encourage you to read both of them because they are both extremely critical concepts in this class there are some things that like it's like yeah it's not so important these two are really important so please make sure to read the handout there's a couple new concepts I want to show you briefly in the beginning and then we're going to begin to put a whole bunch of things together so so far in class what we've done is when you saw Carol and we did a bunch of stuff with Java so far we've shown you kind of a bunch of bits and pieces of things and put some larger pieces together in today's the day where it really all comes together and a whole bunch of stuff that we've talked about before where I said oh well later on this will make more sense today's the day when hopefully that will all make sense so first thing to cover just very briefly by something called strings and if you've been reading along in the book you've seen some references to strings we haven't talked about them in class and now it's time that we spent a little bit of time talking about strings and about another week and a half we'll spend a whole bunch of time talking about strings but you should at least get a little introduction to them so what is a string a string is just the type like we had instantly had doubles and you know those boolean stuff like that string except string starts with a capital S it's not lowercase is actually a type and so we can declare variables of this type like we can have some variable called STR which is a string and what is a string hold the what string really sort of means is a string of characters it's a piece of text is all a string is and the way we usually denote a string is its inside double quotes or sort of you know the quote that were used to so we might have some string and initialize it by setting it equal to hello space there so it's perfectly fine to have spaces and other kinds of characters inside of a string and basically it's just a piece of text that says hello there right it's just one variable happens to have this value hello there and so the important thing is it's text enclosed in double quotes and you can think of the text that you actually assign to the string you can use things on it like concatenation just like you did in a print line' when you actually want to print some stuff on the screen we use the plus operation the concatenate piece of text together what we can do that with strings so we could have some string will call this string name and we might set name equal to Bob and inside double quotes and we might have some integer age which is just set to 20 and then we might have some other string so some other string s which we want to set to be something like quote name colon plus and then whatever the name actually is in this other string so name what that'll do is concatenate the word Bob on to name colon and then maybe we want to concatenate onto that something like age and then concatenate onto that the value of the variable age and so what we'll get here is we'll get something that in the end s is just some variable so it's just some box that contains something and what will contain is name colon then concatenate it on with whatever name evaluated to will name when we look it up in the box is just Bob so it'll say name Bob and then concatenate on to space age colon and then whatever the value sorry over the colon here and then the value of whatever age was which is 20 just like you know this would way work in a print Lynn if you were to say print line and have parens around this whole thing you would expect it to print this out you could actually just assign that to a string okay so same sort of concatenation works and then you might wonder well you know how do you sort of sign these strings or get these strings you can sort of a sign what we refer to as a literal which is an actual value to the string you can build up a string by concatenating a bunch of other stuff together sometimes you want to read in some text from the user and there's a little method called read just like read int and redouble where you give it some piece of text that it's going to display like you know question mark because it's going to ask for something and what it gives you back is basically the whole line that the user typed in so it's not just looking front enter a double but if they type in a whole line of text including characters it gives you that back as a string that's what it returns and you can assign it somewhere like some variable we might call line that's out type string okay so you should just you know at this level see what a string is understand it be able to get them from users in about a week and a half we'll do a whole bunch of funky things with strings and get into the nitty-gritty but at this point this is just to give you a little bit of an idea as to what they are because we're going to actually use them later on today and there are some references in the book that hopefully will make a little bit more sense but up to now we didn't actually need them so we just kind of deferred the discussion okay so any questions about string all right so the next big thing here is the real big topic that we're going to cover today is writing our own classes so this whole time when we've been writing classes right so we would write something like my program and it would extend console program and we'd have all of our methods and stuff inside of that class for my program wouldn't it be kind of interesting to actually have multiple classes because in the days of yore we talked about a Java program is really just comprised of multiple classes so today's the day where you learn how to write other classes other than just sort of the main program that you're actually writing so what's the general form for actually writing a class the idea is we say public four right now all of our classes are going to be public the word class and then we give the name of the class so this should just be familiar to you just like when we wrote programs that extended console program we had some name here I'll put an underline to indicate that that's not actually literal name you just give it a name and then potentially you can also add on to this extends and then some superclass and so what you're saying is that you're creating a new class with this name that potentially extends some other class okay and then inside you have some open brace you have the body inside here so this could be all your methods it could also be variables that are defined as we talked about before various instance variables or aivars in the class and then the close of the class ok now this part over here I'll put sort of in dash friends because it's optional you actually don't have to extend something as part of a class if you don't extend something as part of a class what Java sort of says is the default is everything that in my universe at least for the time being are classes so if you don't tell me that you're extending some existing class there are some default class called object which by default you will extend if you don't say extend some other existing class so everything at the end of the day in Javas world sort of moves up the chain or the hierarchy that we talked about a couple weeks ago and ends up an object so everything at the end of the day really is an object and if you're not extending something in particular then you're just directly an object okay so if you want to write this class what you end up doing is you want to create a new file and I'll show you how to do that in Eclipse in just a second but basically let's sort of put in the Box here the name of the file should be we kind of define it to be whatever the class name was and then a dot Java at the end and the dot Java lets us know that this is a Java program so if this thing happen over here this class happens to be class Bob we would have some file Bob dot Java that would be where all the code that we write for the class Bob actually lives okay and the stuff that's going to be inside here is all the stuff like the methods and variables and constants which are just a particular form of variable there's just a final variable so they get no other value okay and the stuff that you have inside here are the methods and the variables have certain visibility associated with them as we talked about before right these things can either be public or they can be private okay and the difference between those two hopefully it'll make a little bit more sense is methods or variables that are public or what we refer to as being exported out of the class other classes so if you write a whole bunch of classes let's say we write three classes and so I have my class Bob and Bob might have it at some public method well if I have some other class Mary Mary can actually call the public methods of Bob okay so if it's public anyone can access them if they're private they can only be accessed by other methods inside of the class so if I have some method inside Bob or variable inside Bob that's private the only things that can refer to it are other methods inside Bob if I have some other class Mary the methods in Mary cannot refer to the private members or the private elements of Bob so that's the important thing to keep in mind there's a couple other notions there's a notion known as protected and we'll talk about that potentially toward the end of class for right now you don't need to worry about it the thing you do want to keep in mind is that most things in classes will actually be private unless there's a good reason to make them public right in some sense think about yourself right you want to have some notion of privacy you don't want to just broadcast to the world or let the world to be able to come in and say hey you know you have some variable here which is like you know your age and I'm just going to go someone else is going to go and modify your age like that would kind of bother you right and so most things you're like well maybe not it depends if they make me 21 um maybe not right so most things you keep private unless there's a good reason to keep them public to actually make them public until the run method that we talked about so far actually sort of told you it needs to be public most things will be private and I'll show you some examples of classes where we look at things that are private versus public okay so any question about that what public or private actually means or sort of the general notion of how we would define the class hopefully that's familiar to you because you've seen it before huh right there's someone else us the 106a people who provided actually the ACM people who provided the libraries for you that use that call your run method automatically when a program starts so that's what's actually going on and when we get toward the end of the class I'll kind of lift the covers on what's going on there yeah exactly unless you want people in Timbuktu touching stuff they shouldn't be touching it should be private right the way I like to think about it is think about your private parts right you like to keep them private you don't want them to be public most things that you have on your body or private you are an object so most things in an object or private alright just keep that in mind so with that said let's actually go and create a new class it's kind of fun to create classes so I want to create a new class so what I'm going to do is I'm going to get my Eclipse out I'm going to fire it up and the way you can actually create a new class in Eclipse is over here in this little window that we haven't done all that much stuff with so far usually we give you some folder that's called like assignment 1 or assignments you and you work on it if you right click on the name of that folder and if you happen to be a Mac person that's the same thing as control clicking on that you'll get this big scary menu that comes up and you want to pick new and when you pick new you pick class so that's all that's going on right click on the name of the folder pick new and pick class and what happens now is this thing comes up and it says create a new Java class and there's all these fields and you know things layers like dogs and cats sleeping together it's just totally out of control and the only thing you need to worry about here is what are you going to name your class ok and so maybe we want to write some class I'll just call this my counter because I'm going to write a little class the crates counter notice when I started typing as soon as I started having let me get rid of this I'll start typing again my counter anyone see what happened Eclipse had a cow and the cow that it had was up here up at the top it says the use of the default package is discouraged then you sit there and you think 1 what is the default package and 2 wise it's used discouraged and the important thing to keep in mind is you don't care this one of those moments in your life where you're going to be rebellious and you're like bring it on I'm in the default package that's life in the city ok and what a package really is the package is just a collection of classes a set of classes that make sense together Java provides a facility to say we're going to put them all in the same package right now we're not going to define a whole bunch of classes that all work together so we don't need to worry about packages so all of our classes that we write are going to be in the default package which means kind of the unnamed package is just the start of the package that everyone's a part of unless they're a part of some other package ok so it says oh it's discouraged and you're like I don't care I'm in the default package you know I'm living for big Gusto's and then you do something extremely complicated which is you click finish' okay and guess what you just created a new class okay now a couple things to keep in mind over here in your little project that you have there is now an entry called my talent or Java remember we just named the class counter guess what Eclipse did for you it did this it created for you a file automatically ending with Java that's name matched the name of the class good times what else did it do for you it created what we refer to as a stub it said I'm going to create an empty class for you're going to create a class called my counter so what I'm going to do is create for you the empty shell right it gives you basically two lines of code and one of them is a brace so it's not providing a whole lot to you but it's like oh you got to define a class like aren't we excited to write a class and you're like all right let's actually write the class so what I want to do is let's go ahead and actually write a class okay and the class that we're going to write is something that's basically a counter or I'll refer to also as an incremental it's a very simple idea here what I'm going to create is a class that is going to allow me to get essentially on numeric values that are sequentially coming from each other you might say why would I want to do this this the kind of thing say that Stanford would actually want to do when they're assigning UID numbers right they want to have some object somewhere which is the ID number provider and they're like hey you just came to Stanford get me a new ID number and you just came to Stanford get me the next ID number so what I want to have is some way of saying hey create this object for me that just gives me numbers and I'll just ask you for the next number and you just sequentially give me new numbers or how many of you have actually been like at a bakery or something where they have one of those big red wheels that has little tags that you pull out of it that's a counter okay so that's what we're going to write as a class and then we can create objects of this counter type okay so how do we actually create the class this is a little bit different than writing a class that extends a program because we're not writing a full program we're writing a class so we don't have a run method here what we do have is something that's called a constructor and what a constructor is is it's sort of the thing the method that gets called that initializes everything that should be going on with this class now here's the properties of the constructor first of all we're going to make a public at least for right now all the Constructors are going to see you're going to be public a constructor does not return a value so we just skip the whole notion of a return type and we give the name of the constructor the same name as the name of the class so we'd say public my counter okay and now at this point we have no return type then we provide whatever parameters we're going to take in here now what I'm going to do for my little counter is I'm going to be kind of funky I'm not necessarily to start at one I'm going to allow someone to say hey you know like Stanford IDs don't start at one like they actually started it like 30 some odd million right and most of you actually have one that's like in the 40 odd millions you're probably 50 odd millions or what are you up to this is your first ID number five now how many people have five anyone have a six and we have a four anyone have a three yeah good times it's come a long way evidently we've admitted 20 million students in the last 15 years um so what we're going to allow my counter to do is have some starting value so we're going to specify parameters start value that's going to be essentially where we want this counter to start and now you think for a moment you think hey meirin we got to do something with that start value right this is state of the object that we need to keep around somehow we need to start off by saying this counter starts at start value and every time you ask me for a new value of the counter I'm going to give you a new number that means I need to keep track between method calls of what the old number was right so if I need to keep track of something between method calls what am I going to need instance variable good times few people over here one person lying on the floor down there so what I'm going to have is an instance variable I'll define the instance variable down at the bottom I'm going to make the instance variable private because I don't want someone being able to muck with my instance variable so I'm going to have private int and I'll just call this counter so this is my instance variable over here and so what I'm going to do is in my constructor I'm going to say hey initialize that counter to be equal to whatever start value the user gave okay so I have my own little instance variable here every counter object is going to have its own little counter variable and I'm just going to start it off by giving it whatever value the user told me to set it to when they created an object of this type and I'll show you in just a second how we create an object of this type now the other thing we could do that's kind of funky is you can actually have more than one constructor you have multiple constructors that have the same form they're all public at least for so far they return no type but the thing that differentiates them in the way the computer knows which constructor to actually use is what their parameters are so we just created a constructor that has one parameter I'm also going to create another constructor that has no parameters so someone can actually create a counter without telling me what the starting value is well what is the starting value if they don't give me one I still need to assign one so I'm going to say hey if you didn't give me one I'm going to set your starting I'm going to just set it the starting value to be one because most the time when people want to counter they just want to count from one but if you want to do something funky like have ID numbers for university you can tell me the starting value and so I'll show you in just a second how we actually create objects of this type and when we create objects how it differentiates between whether to call this method up here with a parameter or this method over here without a parameter okay a couple other things we need to do we need to find specify some way of saying give me the next value right how do I get new numbers how do I request new numbers from this counter well I need to have some method this method is going to return for me an integer because my counter is just integers and I'll call this next value it takes in no parameters because I don't need to tell you anything I don't need to tell the object anything to get the next value I just say hey buddy next value and it gives me the next value so the way it's going to give me the next value is it's going to give me whatever value the counter has right now okay so I might be inclined to say return counter what's the problem with doing that what happens the next time I call next value I return the same that's not very exciting right you go into the bakery and you're like hey I got number one you look around there's 300 other people have number one it fights break out it's bad times so what we need to do is we need to say hey I need to keep track of what value the counter is currently right now because that's what I'm going to return to you so I'm going to have some temporary and this temporary is a local variable it only needs to live inside this method for the lifetime of this method and I will initialize that temporary to be whatever the current counter value is then I'll go ahead and add one to the counter value so I'll increment the counter so the number next time this gets called is going to be one higher and what am I going to do now when I return any ideas returned the temporary right the temporary is just the thing I'll actually put in friends even though I don't need to that's the what the value of counter started at when this method was first called so I say Oh store off a copy of it add one to the counter because next time it'll be one greater in return whatever the old value was in temporary and after this functions gone temporary gets blown away and it's like hey I was a local variable I gave my life for the method we're like oh thank you very much temporary I was that was very you know courageous of you but we you know you're gone now but you managed to return this value that you store it so good times you actually did what we needed you to do okay and this is my whole class okay so any questions about this class now let me show you one other thing before we actually make use of this class okay and it's a way that we could have actually done things slightly differently okay so when we actually created the class here is our constructor in this case what I've done it I've just renamed the class from my counter to be incrementer because incrementer is kind of the more funky computer science you turn 40 and incrementer is something that adds one to something in counts so rather than my counter which is just all fuzzy in feels like oh it's my counter but people might think Oh your counter is actually like is that like the restaurant in Palo Alto like this gives you burgers anyone ever eaten there it's good time um and they didn't even pay for that product placement I gotta say we'll call it incrementer okay but same kind of thing here we're going to have some constructor for incrementer it's going to take some start value I'm just showing one of the constructors here and one thing you might say right is okay what are you know the properties just to reiterate if constructors the name of the class is the same as the constructor name the constructor does not specify return type it's responsible for initializing whatever values we care about in the object and this puppy gets called when an object is created and I'll show you an example just like you created graphical objects in the past we're going to create an object of type incrementer in just a second and I'll show you the code for that but that's when this implementer method actually gets invoked okay so one thing that people think about when they see this is hey you have the start value thing and then over here you call a counter why don't you just count it call a counter both places like why don't you rewrite the code like that okay what happens when we do that is there any issue with doing that like ah there's the one part of you that's like oh that looks so clean like counter equals counter and then there's a part of you should get really uneasy right because you see this line here and that line does nothing it assigns the same value back to itself and you're like but but I wanted this counter to be like my instance variable counter and I wanted this counter to be my parameter counter can't the computer just figure that out no or as my one-year-old son says no no that's he's learned that word and like nothing he wants to do nothing anymore because everything is no now and you can't do that here because sometimes it will prevent you so the problem here is that the parameter counter is actually getting assigned to itself you're like hey counter here before was the instance variable what's going on if you have a parameter that has the same name as one of your instance variables you get something called shadowing what shadowing is is when I refer to some variable the first place I look is do I have any parameters or local variables that have that name if I do then that's what I'm referring to if I don't have any parameters or local variables with that name then I check to see if I have an instance variable with that name so there's actually an order in which I check for these names and because in this case I have a parameter named counter this counter is referring to that parameter and this counter is referring to that parameter in the previous case I didn't have a parameter named counter so it said do I have a parameter named counter no do I have an instance variable named counter yes so it uses the instance variable so you could say hey is there way it can force it to know the difference between the two counters and the answer there is actually yes okay so even though there's a problem here we can fix this and the way we fix this is with a notion called this the way you can think of this is this is always referring to the receiving object what does that mean and that's a mouthful it means that when some method gets called remember method gets called there's always some object of that method is getting called on well when we call that method inside the method we can refer to this dachau 'nor which says refer to myself my own objects counter don't refer to my parameter counter so this dot counter will look for an instance variable directly it will not look for a local variable it will not look for a parameter so here when I say this counter it says you have an instance variable named counter that's what this dot counter is referring to this counter over here it says hey I don't have any kind of qualifier let me check the parameters and local variables first I have a parameter named counter so that's what the counter over here is actually referring to now this is kind of ugly syntax there are some reasons to use it here and there but it's ugly syntax the way to think about this is just give them different names that's the easiest way to do it right keep the names of your parameters distinct from the name of your instance variables and I'll just be no confusion with this or that or whatever you just keep the names distinct and it's the preferred route you want to think about writing programs that require the human to think less when they're actually looking at the program you're like that's really weird I thought computer science was all about thinking yeah it's about thinking higher up the food chain you don't want to worry about little details like this and get caught in these weird shadowing effects or aliasing effects you just want to say yeah they're distinct and then it's clear okay so any questions about that kind of a funky concept but it's just important for you to see it so with that said let's actually look at not my counter anymore we sort of wrote the bare-bones code for my counter but here's the full-fledged incremental version right and so when we're now computer scientists and we think about good programming style we have some comment for the class so just like programs you wrote you want to have some comment for the whole class you want to have some comment per method you write so this is all the same code we just wrote now it's just commented ok so good programming style uh-huh because if I declare it every time there is no way of me being able to keep track of what its previous value was so I need that's the critical concept of an instance variable right I need to keep track of some information between method calls if I didn't like temp right I didn't care what temp was the last time I called next value it's just a local variable and it goes away but counter I need to keep track of so how do I actually use counter I wrote a program called use counter right just because I love you that much I really do but but not in that kind of way alright so use counter basically just a Java program that is a program right so it extends console program just like you're used to I'm changing the font you don't need to worry about this line all this mine does it just makes the font bigger so when I run the program you can actually see the text because there's people who are having trouble seeing the output text when I ran programs now how do I create objects of this class this is just like you saw with graphical objects okay so let me scroll this down a little bit what's going on is if I want to create some new counter or some new incrementer i specify the type of the variable incrementer i give it a name I'll count it count 1 and because I want to create an object I sort of go to the incrementer Factory and say give me a new incrementer ok when I say new and the name of a class what I get is a new object of that class so at this point when I say new incrementer a new incrementer object is created for me that is when the constructor for that object gets invoked so that constructor thing we just wrote that initializes the object the place it gets called is when you ask for a new one of the class when you get a new object the Constructors invoked which version of the constructor does it invoke if you have multiple versions it depends on the parameters you give right we created two versions one without a parameter if you didn't specify the parameter it set the counter starting at 1 1 with a parameter so if you specify a parameter a test hey there was a version of this that had a parameter that's the version that's going to get invoked and so it's going to set the beginning counter to 1000 ok any questions about that so what are we going to do now what we're going to do is write out some values of the counter and count up so what I'm going to do is write a method this method is going to take an object as a parameter there's no reason why I can't write parameters just have some type and some name so this count five times method is not going to return anything but it's going to take as a parameter something of type incrementer that I'll just call counter and what it's going to do is very simple it's going to loop through five times and just print out the next five values of that counter right so that's all it does it just pulls the next five tickets from the counter and writes them out to the screen so I'm going to say what are the first five values for count one and call this function what are the first five values for count two and call the function passing and count two and what are another five values for count one okay so let me go ahead and run this program you can see what's going on so if I run this do to do to do there's what I get so I say the first five values for count one remember count one started with a counter of one it gives me one two three four five then I asked for the first five values of count two counts who started a thousand so I get a thousand up to a thousand and four then I asked for the next five values of count one and I get six seven eight nine ten now this all seems fairly straightforward except for one fact that should slightly disturb you is there anything that slightly disturbs you you're like no man why should I be disturbed like I know this how the program works because you just ran it that way the thing that should slightly disturb you is the conversation we had last time or we talked about when you pass a parameter to something you get a copy of that parameter or you get a copy of that thing that you're passing right so the interesting thing that's going on is you would think well you're passing count 1 here when you pass count 1 there shouldn't you have gotten a copy of the count 1 that's started with its counter of 1 so when I counted up here shouldn't have it only been counting in that copy and so when it was done here that copy should have gone away and when you returned over here your counter should have still been 1 right if we were doing integers that's sort of what would have happened but the thing that's different between integers and doubles and objects that's the important thing to think about objects when you pass an object as a parameter you are not passing a copy of the object you're passing what we refer to as a reference to the object which you're actually passing the object itself ok so what we think of as a reference is really there's a way to point to the object so let's say you're an object right when I'm over here and I say give me a new object you're sort of created you come into being and what count one really is is just a way of pointing to you ok and so when I say hey count five times count one what I'm actually passing is a copy of my finger I know I got a little weird but it points to you so when we count through five times you're the one counting five times and then when we come back over here and I count a call count one again I'm passing another copy of my finger that's pointing to the same place so you're the same object that was invoked before and you give me the next five values so critical thing to remember when you are passing a object is a parameter you are actually in some sense passing the object itself the way you can think about this is it's like the Mafia we know where objects live and if I know where you live when I'm doing something when I like come to your house and put a horse head in your bed or I'm like you know getting the next value or whatever it's you and it's you every time because I know where you live with integers we don't know where they live we just pass copies here's a copy of a double here's a copy of an integer we don't know where they live that's perfectly fine with objects we know where they live and so what you're actually passing is you're passing where that object lives and so that way you're always referring to the same object because you're referring the same address where that object lives you're always looking up the object at the same place any questions about that that's kind of a critical concept uh-huh when we write a program that makes use of a class that we've written how does it know to access that class oh well because when you're creating your classes over here you're creating all your classes in this default package and they're all in the same project so when you say give me a new incrementer it goes and looks through these and says hey do you have an incremental class over there and that's how it actually knows huh because we already counted one two three four five so the counter the value that's actually being stored for the counter is currently six not my doing I was actually on the swim team once but I don't think I ever would have ran in speedos through a group of three hundred people all right good times any other questions that's why I doubt or question after that all right so one other thing we can do is just moving right along like that never happened one thing we can also do that's kind of funky is remember when we have our counter our incrementer we have this instance variable okay there is another kind of variable which I never told you about before because blacks I did tell you about I just didn't give you its actual name before but now you're sort of old enough to you know follow obi-wan on some damn-fool crusade so I'll tell you what the real deal is besides no it's terrible isn't it go see Star Wars it's so good but the basic idea is so far you've seen things like local variables and you've seen instance variables there is a new kind of variable and it is called a class variable great class var what a class variable is it is a variable that is shared by all objects of that class there is one variable that all objects of that class share that's the funky concept okay an instance variable each object of that class has that a different version of that variable right so if we have some counter over here and we have some count one and some count two and they each have an instance variable that we just define each of them has its own box if I were to create a class variable there is one variable counter that all objects count one count to all objects of the type or of the class that this class variable is in are all referring to the same one single box okay now there are some times you want to do that I'll just show you a very simple example of how that works and how you actually specify it's the way you specify is an instance variable you just specified if it was public or private you specified its type and you gave it a name a class variable you add this word called static and sometimes class variables as a result to refer to as static variables and you've seen static before when did you actually see static used in conjunction with a variable constants right why did we make them class variables by adding static because it doesn't make sense for two different objects that are circles to have their own copy of the constant value pi right pi is in some sense some universal for all circles so it would be shared as a class variable among all circles right so even though it was a constant if we didn't say static we would have gotten one of those constant values for every circle we created for example we want to just have one that's share it so we call it static but you can have static variables that are not necessarily constants they don't have to be final so let me show you an example on the computer okay we come over here here's our incrementer that we just wrote and we say private static encounter so what I've now done is instead of creating an instance variable I have created a class variable how does this change the program so let me save this and run this what this will now do is all of the things that I create that are incrementer are all referring to the same counter and you're like whoa that's kind of funky yeah let me show you what actually happens so when I run use counter I get a thousand through a thousand and four then I get a thousand and five three thousand and nine then I get a thousand ten through a thousand 14 and you're like whoa what happened there right let me explain to you what happened here and hopefully it'll be clear like why did it start a thousand why didn't it start at one what was actually going on okay what's going on if I actually look at use counter is remember there is only one counter variable for all objects of the class this first count one comes along and says hey give me a new object that's an incrementer and we say okay and we said it's counter to be zero or we said it's counter to be one right that's what the constructor did then I say hey crate for me another counter and it says okay here's another increment or over here I'm now setting that counter variable to be a thousand and you're like oh oh that's the same counter variable the count one was using too because now they're both sharing the same variable and that variable is now a thousand right the old value of one just got clobbered by this guy because it's referring to that same class variable there's only one counter variable among all objects of the class so now when I count the first five values of count one it's got a thousand it counts up to a thousand and for that thousand and four is shared by all instances of the class so when I do the next five for count to its starting at a thousand and five and it counts from a thousand and five through a thousand and nine and then when I do count one again count one sharing that thousand and nine and that's why we get a thousand and ten through a thousand 14 hey any questions about that uh-huh oh yeah microphone would be good and let me guess what your question is if you switch the order yes you would actually start at zero because the first constructor would initialize the var you'd start at one the first constructor would initialize the value of a thousand the second constructor would overwrite the thousand with one and then you'd count from one it's it's that everyone to know I have this this fleeting ten-second ability to read minds and it goes away very quickly if only it worked at home it doesn't all right so with that said it's time for something completely different so any questions about instance variables versus class variables uh-huh uh-huh maybe we should talk about that offline because it'd be good to know what particular thing you're referring to but most the time for a lot of intents and purposes in this class the main time you'll actually see static variables are when they're actually constants there's the very few times when you actually have a static variable that's not a final variable it's not a constant but if you're interested we could certainly talk about that offline okay so with that said there's a funky concept called Javadoc okay and now you're old enough to learn about Javadoc okay and all Javadoc really is is it's basically Java's documentation system this is just a little side point and the reason why I'm giving this aside to you is you're going to see Javadoc in just second we're going to write another class using Java doc the difference between regular comments and Java doc doc comments is very simple Java doc comments start with a slash and two stars instead of just one star but they still end with a star in a single slash so comments that are in that form that start with a slash and two stars are called Java dot comments and you'll see what that means in just a second there is also in the comments you can put special tags that are understood by the Java doc system this is just the system that's going to generate HTML pages that explain what your code does via its comment so your comments actually serve a purpose now your comments are going to beautifully get transformed into HTML that someone else can look at when they're actually trying to understand what your class does instead of having to go through code they can just look at a little web page so there's some special tags like add sign pram or add sign result that specify what is a parameter of the function you're writing or the result if the function is actually returning something and I'll show you examples of that right now okay so here is a method and this method might be some method we have that just sets the number of units someone earned so it's called set units it takes in some number of units as a double and let's say we have some instance variable somewhere units earned which is like how many units you've earned to call it so far we just get sets units this comment here is a javadoc comment right starts with star with slash two stars and with a star slash inside the comment we still comment what the function does just like a normal comment we specify whatever we want to explain the user additionally we can have some special tags like at pram and the way a pram works is for every one of your parameters you specify at four am then you specify the name of the parameter so that's why the words would kind of went funky because the name of the parameters units that's the next token here right or the next word is basically units and then what that parameter actually means the number of units earned so for human reading it's not necessarily the most legible thing in the world but after you've seen it for a while you just kind of internalize it but the computer can actually understand that very well and produce some nice documentation so let me show you an example of this it turns out if you're actually interested there's Javadoc for all of the ACM libraries all the libraries that we're using in this class if you want to dig into them if you go to this URL jtf which stands for java task force ATAC emmerich slash Javadoc slash student because it's the student version of the Java doc it's just a beautiful thing you can actually see the Java doc for all of the ACM libraries okay so you can just sort of to your heart's content look them over but let's just look at one particular example remember random generator that we sort of looked at together last time from the ACM libraries let me just show you the Java doc for that so you get a sense for what's actually going on wait so all Java doc is is it's HTML right it brings up a web browser and what it explains in here is here is class random generator right this is stuff that got automatically generated based on the comments in the code it says ACM util random generator is actually derived from Java util random so it's actually a subclass of Java util random and it tells us that that by saying that actually this public class random generator extends random so it's in fact a subclass and there's a whole bunch of stuff there that explains how this class actually works and how you get random generator get instance to get a version of it but it also what's generated for you very nicely in these nice HTML tables or things like hey here is the constructor constructor has no arguments that's how you might potentially create a new random generator if you wanted to but in fact most the time what you want to do is get instance so for all of the methods it has the name of the method it has basically the form of the method which is the method and then whatever parameters it takes and then whatever comments you have about that method okay the other interesting thing about this let's kind of scroll down a little bit is it tells you which methods are kind of built in and which methods actually got inherited from your shoe per class right so we mentioned that a random generator is an object that extends random well some of the methods are actually defined and random generator specifically some of the methods are inherited from this thing called random it doesn't actually make a difference which ones are hair dirt or not but you get kind of all this text you get even more text down here so if you want to look at the excruciating details of next boolean right that takes in some double P it tells us what the usage is how do you use next boolean and what are its parameters this is where those at per am little tag that was in there there's an app pram tag that says P and then has this comment and this automatically gets turned into nice HTML okay so any time you have questions about what something in the ACM library does or what methods are actually available to you for a particular object you can just actually go look at the Java doc you don't need to scrounge through code it's actually just HTML you can browse on a web browser by going to that URL I gave you and kind of search around okay but the reason for sort of showing you all this one is to let you know that it actually exists the second is we can now put this all together we can create a class that has a bunch of stuff in it that we comment using Java doc and it also makes use of strings and give you one nice big picture at the end okay so what I'm going to do is I'm going to create a class that this class basically is involving a student write something that hopefully you're all extremely familiar with at this point you learn my little thing you go so what a student class is going to provide right it's going to have Javadoc comments so up at the top I have the star the slash star star I thought wasn't a typo that's actually Java doc doc comment and explains what this whole class does so it says what I'm going to do is create a class that keeps track of a student what is information I care about for a student well this is a very simplified form I care about a name of a student their ID number and how many units they've earned that's all I care about for right now right the book has an example that's a little bit more involved but I'm going to give you a real simple example here so what are my constructors how do I create something as a student notice the class student does not extend anything right so all students are just objects right I'm not extending anything else they're just objects one of my constructors for students says hey specify the name and ID for the student as a matter of fact that's going to be my only constructor I'm not going to allow someone to do other kinds of things give me a name which is a string right it's just a piece of text and an integer which is an ID number so we'll assume all ID numbers are integers okay and what it's going to do is keep track of some information about students that are going to be stored as instance variables because every student is going to have their own information for their name which is just student name that's a string student ID which is just an integer and the number of units they've earned so far which I'll keep is a double because you know there are some schools that actually allow like half units for whatever classes they don't hear but other places they actually do so we're just making it a double for generality as opposed to having of unit so these are all private instance variables no one else outside of a student can get in there and muck with these things the only way we can potentially change them is through the methods that are involved in this class okay we're also going to have the number of units that are required to graduate at Stanford that's 180 and we're going to specify that as a constant that is static and final which means all students share the same number of units to graduate and unfortunately for you you can't say hey you know what yeah I'm just going to set units graduate to be like 10 right wouldn't that be fun like you take 106 a you take ihum and you're done final baby yeah you're not changing this it's 180 until the cows come home okay so that's why it's a constant as opposed to just being a class variable that's actually modifiable so what are all the things we allow someone to do in here okay the things we allow someone to do are for exam to get the name of a student once I've created a student write the student name variable is private I can't actually refer to that variable outside of this class so how do I ask you for your name after you've been created right so you were just created as a new student at Stanford and I'm like oh what's your name and I want to kind of come over and get like a little close and be like hey can I touch your variables you're like no man like this is wrong so I'm like Oh what do you have that's public right what can i oh get your name so I can add in what's your name okey so I get back a string a key from your object right I can't actually touch any of the private parts thank God all right ID number same kind of deal right I can't go in and see what's right II like I'm not going to go on your wall and ply your ID card me like oh ID number right let me get out my magic marker and change it right it's in it only way I can get it is by asking you for it and if you've made that public than I can get that information from you okay by making the method public a few other things now here are some funky things set units I actually made to be public which means I can allow someone even though I set the number of units earned is a private variable so I can't directly just go in and modify the variable directly I can call set units and give it some number and it will just change the number of units you have oh yeah I can ask you for how many units you have right so this is a dangerous thing if you think about it right and that's the kind of thing you want to think about in terms of good programming style what do you make public and what do you make private and if red flags go off because you're making things public that shouldn't really be public that's something you want to think about for style get units right this just returns how many units you've actually earned is a double and again you can see we have a return tag here for the Javadoc that says the number of units the student is earned is the thing we're actually returning okay a couple other things real quickly and then I'll show you that we're going to make use of this class okay there's something called increment units which basically just says hey every time you take a class I want to increment the total number of units you have by the number of units in this class so I pass in some value for additional units and I increment your units earned by additional units having enough units that's a predicate method right it returns a boolean and what it basically returns is the number of units earned greater than or equal to this constant for how many units you need to graduate and last but not least and this is a critical one all classes you write should have a method in them called to string a lowercase T uppercase s what to string actually means is get me some textual version of what's the information in this class so to string for a student bring returns back a string which is the student's name plus their ID number in parentheses it does not necessarily specify how many units they've earned that's fun it doesn't need to include all the information that's actually in the object what it just should specify in a nice textual way is the information that you care about displaying about an object if someone wants to display it okay but all classes you write there are not programs right so something that extends console program doesn't need this any other classes should have a two string and that's the whole class so any questions about this class or should I just show you how we use it let me show you how we use it well it's Stanford right you're at Stanford so we got to have a program called Stanford that actually creates students so Stanford is a program that extends console program and again we have some you know thing to increase the font size but we're going to create some new student than Newman there you are there you go and that's pronounced stood not stud I just have to make it short sorry Ben I know so we have some student stood that's a new student and remember we need to specify the name and ID number to initialize that student then Newman your ID number is now a thousand and one there you go I'm going to set your initial number of units at 179 oh I know and then I want to write out how many units you have right I cannot refer to your name and number of units directly I need to ask what's the object right that's the receiver of the message and the message I'm going to send is the name of the method I just wrote stu-dog yet name that returns to me a string which is the name that's been newman i append to that has i append to that the number of units been has and then add the word units at the end of it write that out to the screen then i want to see if ben can graduate so again I print out Ben's name if he can graduate his status by calling has enough units that will return true or false that will write true or false out onto the screen as part of the string okay then takes the s106 a good time so Ben takes es 106a is what's going to get written out and then I increment Ben's units by five because he's now taking CS 1.6 a five unit class and then I ask again can he graduate okay and if he has enough units to graduate I'll say rock on and write out the string version of the object that I have by calling to string so when I actually run this all here's what I get do run in I'm running I want to run Stanford it's just that easy to run Stanford high for a moment you got to feel like John an Essene right and it's it just it's a small school it's like Stanford has one student it's been so Ben Newman has one hundred and seventy nine point zero units right cuz it's a double so puts that point zero at the end of it Ben Newman can graduate we get false back because he doesn't have enough units to graduate but that 179 is stored inside the object right that stood object-- has the 179 then takes us 106 a so we increment that object's number of units by five by calling the appropriate method and then Ben Newman can graduate is now true because he's got 184 units and finally when we say rock on and we call to string what to string gives us back is the name plus the ID number inside paren so it says rock on Ben Newman paren number 1001 okay any questions about that alrighty then have a good weekend and I will see you on Monday
Info
Channel: Stanford
Views: 221,128
Rating: undefined out of 5
Keywords: computer, science, technology, grades, programing, software, variable, names, language, java, string, variables, readline, run, methods, return, constructors, implementing, class, var, javadoc
Id: iYtri45lhtc
Channel Id: undefined
Length: 52min 25sec (3145 seconds)
Published: Thu Jul 03 2008
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.