>> Programming with objects is the predominant way of developing software today. >> Code is organized into pieces called objects. You can use objects written by other people to create your own programs. >> That way, you get to stand on the shoulders of giants instead of having to start from scratch every time. >> In this lesson, you'll look at lots of different examples of objects. You'll learn what they can do and how to make them do it. >> At the end of this lesson, you'll be able to write a program that draws a rocket, flying from earth to mars. I think you'll be impressed with what you'll able to do. >> I'm really excited of what you're going to learn this lesson. Let's get started.
My name is Ellora. I am a junior in computer science at Stanford University. I grew up in the bay area, but actually despite that fact, didn't really intend to study computer science. I entered Stanford three years ago as a Psychology major. And took a computer science class because my friends took them and liked them. And I figured I had to take an engineering class anyway, so why not.
Object-oriented programming is one of those things where, there's just so many reasons to use it that I can't think of a reason not to use it. I think, first of all, so much of the programming that is done in industry today uses objects and object-oriented programming. And you almost cannot be in industry without knowing what these things are. The second reason is that object-oriented programming really falls in line with the way you and I think. So, you and I think of a person as an object having a height and a weight and an eye color. And, all sorts of attributes. And that's exactly how object-oriented programming works. It works the way we think. Which is why it's great to know how to use it, because it'll make your job as a programmer a lot easier.
Hello and welcome to lesson Two of the programming in Java Course. We're going to start a discussion with objects to understand why you might want to know about objects. consider someone that is building a house. It used to be in the olden days that a house was built from nothing but bricks and wood. Nowadays, of course, a builder takes prefabricated components such as this furnace or this water heater and puts them together. You can think of those as the analogue of what an object would be in a programming language. An object is a building block of a program. It is a component with some desired functionality. Just as the water heater over here has some desired functionality for the builder it heats water. In your programs you ask objects to do work. You don't know how they do that and that's okay. Just like if you really think about it do you actually know how a water heater does it's job? Or for that matter, do you care? Here we have a different kind of water heater, a solar water heater and it doesn't really matter how a water heater works as long as it heats water. With an object what's important what it does, not how it does it. That's all very abstract, and, the way one really learns about objects, is to play with them. And I'll show you how you can play with some in BlueJ.
Here we hear from BlueJ. And it would really good idea if you fire up your own BlueJ and move to lesson two days as your project. When you open it, you will see the screen with a Day block here. And this is what gives us objects. Let me show you how to make an object. You right-click on it, and you select the line that says New Day. You can now give it a name. For right now, we'll accept the default. Down here, you'll find your first object. This is how BlueJ represents objects. As little blobs, it's a little-known fact that all objects are red. And to manipulate an object, you again, right-click on it. You can ask it to get the current year. Here's the answer. This particular day is somewhere in That's the day that I recorded this lesson. We can make another day object. And now, let's pick, the first line here. Now, we ask which year month and day we might actually want. Let's fill in something. Then, we'll pick a year of 1964. The month of 11 or November, and the day of 28, as I'm sure everyone remembers, on November 28th, 1964, the first spaceship was, to Mars, was launched. Now here, we have another day object. It looks just like the first one. It has a different name. But if we wanted to find out anything about it, so we can in the same way ask it what's your year, and here it tells us. Now, let's do something more interesting. Let's take our first object here and let's ask it what day comes a hundred days later. Now, it doesn't look like it, but this object now has changed. It has moved itself a hundred days later. Remember, it was originally March 20th. Now, when we ask it what's your month, you'll see it's June. That makes sense, from March, 100 days is June, or maybe it would be July. Somehow, this thing knows how to do this computation. How about the day? It's June 28th. I wouldn't have known how to do that. Except by tediously getting out a calendar and counting the days, but our day object knows. How does it know? I don't know, and I don't care. It doesn't matter. I can use it, as long as I understand what it does for me. So, that's a great example of an object. Something that knows how to do a very specific thing, namely to deal with calendars, just like the water heater knows how to do very specific thing, namely to heat water.
Thanks Kyle. Let's use the day object to do another calculation. If you haven't already booted up BlueJ, you should do it now and open up the days project. Mariner4 launched November 28, 1964. It took 228 days to arrive on Mars. What was its arrival date? Before you do this, I want to show you one more thing that you can do with objects. I've opened up the days project in BlueJ. I can make a day object and now I can quickly see exactly the day that's in here using the two string method. I won't actually do it, because I want you to be able to do this yourself. And try it. But that should make it much quicker. So here are some hints. Use a day object to do the calculation And use the toString method to read the day. Make sure that when you write the arrival date, you use the same format that the toString method uses. And don't worry too much if you don't have BlueJ working yet. You can just skip to the answer video and watch it carefully. There will be more examples you can do soon.
The answer is 1965- 7-14. Here's how we would calculate this using Java Objects. We would create a Day object and specify the year, month and day as November 28th, 1964. If we use the two string method. Shows us what's in this Day object right now, which is exactly what we entered. November 18th, 1964. And then we can add days. That's the flight time. And now, this object has July international standard called ISO 8601. It was chosen for good computer science reasons. There needed to be a standard form used by all the different countries so that data stored in computers could be transferred across borders. They put the year first so that when you sort a date sort of alphabetically or lexicographically, don't have to know that word, it's okay. The dates will show up in chronological order.
The next concept that you need to understand is the concept of classes. Look at these dates. Here we have a date, the date of the Mariner 4 spacecraft launch, another date that happens to be the inauguration of FD Roosevelt. And a third date, the date of the first lunar landing. Now, all of these objects have something in common. They all day objects. In Java, objects that have common behavior are collected into classes. So the day class is the class that contains all of the day objects. And the reason you want to know about this is when you want to find out something about how days work. You will want to look at the documentation of the day class. It tells you what everyday object it is. Let me give you another example of a class. Here is a string object, and another, and another. All these string objects have something in common. They all have the same behavior. And in Java, the String class defines what their common behavior is. You will learn a lot more about the String class in this lesson. Let's go back to our day class for a minute, and think a bit more what it means for objects to have common behavior. It means that they can all do the same kinds of things. Like what can they do? As you've seen when you played with days and BlueJ, any day object lets you get the month, get the year or add days to itself. These actions are called the Methods of the Day class. They are the kinds of things that you can apply to day objects to achieve some kind of functionality. The word method, sounds a bit strange at first, and you should just think of it as terminology. It's just where one calls the actions that you can apply to any of the day objects.
Thanks Kai/g. Let's do an exercise where we match the methods with their classes. Don't worry if you're not sure how to do this yet. I haven't actually given you enough information, just go with your gut. Here's the first one. BirthDay.getmonth. Here, the method is getmonth. "Hello world!".length, here length is the method. Anniversary.addDays, here the method is addDays. And lolcatsPic.draw, here the method is draw. Enter the letter for the class, in the box next to the method call.
Let's start with the ones that we already know. We've seen the getMonth method before, it's part of the day class. Looks like addDays is also part of that day class we've been using. This length method you maybe haven't seen yet, but I can look in front of it and I can see hello world, which I know is a string. And down here, I've got something called lolcatsPic. And it's drawing, which sounds sort of like methods which should go with a picture.
To really understand objects and classes, it's best to work with lots of examples. Let's try another example. And again, it's a great idea if you can do this together with me. In BlueJ navigate to the pictures project in lesson two and you will see here an icon representing a picture class. Let's make an object of that class. Again, I will accept the default name, and here is my object. What can I do with it? Well you know how to find that out. You right click on the object and you get a list of things that tell you the methods. Let's pick a method and in fact we will pick the method called pick. This particular method opens up this file chooser here. That lists whatever image files happen to be available. You can also navigate to other folders but we'll just pick one here. Once you pick a file, a window pops up that shows the image. Now let's see what else we can do. Let's call the pixels method. And it tells me that this particular image has 104,976 pixels. Okay, that's potentially interesting. over here we have method called translate. Let's just play with it to see what it does. It wants two numbers. I will just put in 100 and 200, click on OK. And now look carefully at the planet. as you see, it moved. So the method is not called translate because it doesn't translate this into Lithuanian. Translation is a mathematical way of saying moving and it moved it by 100 pixels in this direction and 200 pixels in that direction. So this is another great example of an object. The object can do certain things. The methods tell you what it can do. In the next exercise you get to play with objects of the picture class.
Thanks, Kai/g. It looks like the picture class has some other methods. In BlueJ, I'm going to create a picture object as we've been doing. And I'm going to fill it with a picture of Jonathan, and here's my picture of Jonathan. I'm going to translate it a little. Translate, and 100. Jonathan can't wait to grow up. Are there any methods in the picture class that we could use to help him out? Let's see. Which of these methods might help him grow up? What about the grow method? If I enter 50 and 50 and then hit OK, what will happen? Does Jonathan grow 50 pixels wider and 50 pixels taller? Does Jonathan grow 50% bigger? Does Jonathan grow 50 pixels on each side? Or does Jonathan grow 50 years older?
The answer is Jonathan grows 50 pixels on each side. Let's see how I figured that out. We're back where we left off in BlueJ. I'm calling the grill method on the picture of Jonathan and passing 50 and 50, but I'm going to cancel that for a moment. Out of curiosity, what is the current width of this picture? Get width. It looks like it's 185. So now, if I call the grow method, like I was going to do before, Jonathan just got bigger. But how much exactly? It's hard to tell whether he grew 50% bigger or 50 pixels on each side bigger? Or, just width, and now it's 285. So, it looks like the width grew by 100 pixels. If it were going to grow by 50%, it would probably have grown by about 190 pixels. So, it sounds to me like it grew 50 pixels this way and 50 pixels this way, and then did the same up and down.
Playing with picture objects in BlueJ is kind of fun. Let me make a couple of picture objects. If you look carefully how I constructed the last object, I filled in the name of the file here. And I'll do it one more time like that. If you do it in this way, you also have to tell the program to draw the objects by selecting the draw method. The first picture appears, and a second picture appears. That looks kind of horrible. Let's have a closer look on how we can make this look nicer. First of all, let's move the rocket a little bit, and let's make the red planet a bit smaller. Well, that's much nicer. But it's a bit tedious to do this with your hands and with clicking and clicking, that's where programming comes in. Here I've written a program that does the same actions, that you've just seen me do by clicking in a java program, a step at a time. We'll understand all of the details pretty soon, but let me show you the basic lay of the land. We're making a picture out of the mariner4 image, we're translating it, we're drawing it, we're making another picture object, we're shrinking it and we're drawing it, and that composes the picture. Now when you operate in this way, you make an object and then you later need to do something to that object. And it's, it's in a program here, it's not in the BlueJ work bench. And then it becomes very important to give names to each of the pictures. You'll notice I call this one rocket. I call this one planet. Those names are names of variables, and that what we're want to discuss next.
Use a variable to store value that you need later. Every variable has a name. Here's how I like to think about variables. A parking space is a great example of a variable. That's where you can store a value here, the car, so that it's there when you need it later. This particular variable has the name JO53. We want to remember that name. And you need that name if you want to find your car later. Now, look at this variable. That's a real Java variable. It also has a name. And when you later want to use use the object. That when you use the name again. So the name is one of the important aspects of declaring a variable.
Let's practice reading variable declarations. What is the variable name in this variable declaration? Picture rocket equals new Picture mariner4.jpg. Is the name picture, rocket, new, or mariner4?
The answer is rocket. If I we want to use this variable again, we're going to use the rocket name.
In Java, a variable can't just hold objects of any type, but one has to specify the type that it can hold. In this parking space analogy, look at this variable here. This particular one holds bicycles and we say that's the type of this variable. Now, look at this variable here. There's the name. And in Java, we write the type before the name. First the type, then the name. String is the type, greeting is the name. String greeting.
Now that you've seen where we write the type in a variable declaration, can you find the type in this one? Picture rocket is a new picture, mariner4.jpg. Is the type picture? Rocket? New? Or, mariner4?
The type here is Picture. The variable name is rocket. We have the methods associated with the picture class. We know that rocket isn't the type, because we already said that rocket is the variable name. New, we haven't seen yet but we'll come back to this and mariner4 is just the name of the picture we are loading. It's not actually the type of object.
When you declare a variable, it's important that you give it an initial value. Look at this variable. It's name is rocketSpeed. It's type is called double. And I'll talk about what double means in just a minute. What I want to show you first is over here, the last part of the variable declaration. And that's the initial value. And it really is important that you always supply an initial value when you declare a variable. Because if you forget, and later use the rocketSpeed variable, that would be an error. Every variable that you used must really have a value. The best time to set the value is right when you declare it. Now, back to the curious type double. That means it's a number that can have a decimal point, such as here, 24,724.573. So, when you see the word double, you should simply think a number with a decimal point. And ignore the curious name. Now, look at this variable declaration. The name is sallyRidesBirthday, the type is the Day class, and the initial value looks like this. You will see soon exactly what this syntax means, but when you look at it, it seems intuitively clear, we make a new Day object with a date 1951, May
Here's another variable declaration. It's a little bit different from the ones you've just seen. This variable has type int. Int stands for integer. You can use a variable with this type to save positive and negative numbers without fractional parts. Now that you know what int means, take another look at this variable declaration. What is the initial value of the variable in this variable declaration? Is it int, mannedMoonLandings, 6, or there isn't one?
The answer is 6. Int is the type, mannedMoonLandings was the variable name, and
There's one more useful aspect about declaring variables, namely comments. Have a look at this variable declaration, we have a travelTime of 228 days. When you read it you probably ask yourself, for which trip? Now I can tell you for which trip, but when you write code it's very common that you look at your code months or years later, or someone else looks at the code. And then they would really like to know more of an explanation. In Java, we use comments to give such an explanation. Notice, these 2 slashes, they are the comment marker. Anything that's after the slashes is ignored by the compiler. It's just there for humans. To understand the code. You can write anything at all after the comment marks, and the compiler won't care. But o course, if you write nonsense like this, the humans who read your code may hate you. Comments are for humans. Use a comment whenever you need to explain something that might be difficult to understand for the human reader.
Let's do another calculation with the Day object. Astronaut Sally Ride was born on May 26th, 1951. She died on July 23rd, 2012. How many days was she alive? You should put your answer in this box. You should use BlueJ for this. Open up the Days2 project, and here are a couple of hints. You'll want to make variables for birthday and lastDay. And then you'll want to call lastDay.daysFrom(birthday) and print the result. Don't worry too much if BlueJ isn't working for you. Just look around the video, and you'll find a link to the Udacity Java editor that you can use.
The answer is 22,339 days. The way that we would figure this out, is that we would open up Bluejay, and we would go into this days alive printer, and start editing it. And the main method right here, we would first create a variable birthday. Initialize to Sally Ride's Birthday, and another variable, Last Day, initialized to Sally Ride's Last Day. Then we do the calculation and put that in another variable. Here you can see that the daysAlive is an int. And then we print out the result. Which is in daysAlive. I compiled, and I got no syntax errors, so let's try running this thing. I go to the daysAlive printer, run the main method, and I get my answer, 22,281. That doesn't match what I got before, one second. Looks like there was a bug. This shouldn't be May 26th, it should be July 23rd. Let's compile this again. Close it. Try running our main method again. And this time we got the answer I expected, 22,339.
So I got this program to work, but I send this program to my friend, she's going to be a little bit confused. She won't know what it does. Let's look at the program again. There's nothing in here that says that the point of this program is to calculate the number of days that Sally Ride lived. So why don't you go back, write some comments for your code, and then I'll show you the comments that I might have written.
So, I want to indicate what the overall purpose of the program was. So, right at the top, I'm going ti add a comment that says calculate the number of days that Sally Ride lived. Now, I'm going to look at my variables. Seems like in the context of Sally Ride having lived, the birthday is pretty obviously Sally Ride's birthday. And the last day is probably Sally Ride's last day. Days alive would be Sally rides days alive. Seems like that explains most of the lines of this program.
You've now seen a lot of variable declarations. I've seen a lot in my life. I've written a lot in my life. Here's a bunch more. Some of these have mistakes in them. Can you match each variable declaration to a description of the mistake? The possible mistakes are, the variables can only contain letters and numbers. B, it's always a good idea to include an initial value. Variable type doesn't match initial value type. Variable has a bad type. No mistake, this variable declaration is fine. Variable declarations need a semicolon. And variable declarations must have types.
Let's look at the first one. This variable declaration says var x equals 13. Well, var isn't a type that we've seen yet. So it looks like the answer is D. The variable has a bad type. Let's look at the next one. Int X equals in quotation marks 13. Well, int usually takes a number. And 13 is actually a string. So it looks like these don't match. So the answer is c. The variable type doesn't match the initial value type. The next one, double x equals 13.0. Well, we're missing the semicolon. That was an option. Looks like F. Int lucky number equals 13. That one's a little bit trickier, but it looks like there's a space in what we meant to be our variable name, lucky number. We can't have spaces in variable names. they can only contain letters and numbers, so that would be a, x equals 13. Well, we don't know if this is right or not because we don't know if x is actually an int. The answer is g, variable declarations must have types. Int x, we haven't given any initial value. It's always a good idea to include an initial value. Int lucky number equals 13. This one looks good to me, so there is no mistake.
Variables are called variables because they can vary. Here's a variable. It's initial value is 228, but I can vary that if the need arises. Maybe the trip took longer than I thought. Here I'm setting the variable to a different value. Note that. The declaration looks almost the same as the assignment, where I assign a new value to an existing variable. The only way you can tell them apart is that the assignment has no type. The declaration has the type in here. The assignment looks just like a declaration except there's no type. That tips us off that traveltime is an existing variable, whereas over here where we say int traveltime, it is a new variable. One way of thinking about a variable is as a little box with a name. Of course, the value is inside the box, and it can vary. As a result, of such an assignment. Now we've assigned a new value, to the variable, and the new value is stored, in the little box.
We've covered a lot of ground in the last few units. You've learned how to declare variables, and I want to come back to the question, what do you do with a variable once you've declared it. Here we have a variable, planet. It's of type picture, and it's somehow initialized. Now I want to use the variable. I want to call a method on it. What methods can I call? And when I pick a method, what values should I give it? That's what the Public Interface of the Class tells us. It tells me, which methods I can use and what values I should supply. Let me give you an analogy. The public interface of a car is all of the buttons and gizmos that you see here on the dashboard. A while ago, I was driving along in this rental car I could not figure out how to turn on the dome light, so I had to pull out the owners manual. The public interface of the class is also described in a kind of owners manual, called javadoc. That's the owners manual of a class or of a set of classes, let's have a look at javadoc.
The classes, that, come with this course, such as the Picture class here, all have an owner's manual. Here is how you can find it. Select the Tools menu, Project Documentation. And a browser window will pop up. Here it is. As you can see, we have the documentation of the Picture class. As you scroll through it, you will find a method summary. For example, here's the grow method and you can see it says resizes this picture both horizontally and vertically. When you click on the link, a detailed explanation pops up. And here it explains that you need to feed two numbers that are called dw and dh. And they're further described down here. The first number is the amount by which to re size the width on each side. and the other the amount by which to re size the height on each side. That's how it works for the classes that we give you. If you use a standard library class such as the String class, you instead want to look at the official documentation. I've made a bookmark for it and I suggest you do the same. Here it is. On the left, you have a listing of all of the various classes. They're many of them, most of which you never need to know. Let's find the String class. Here it is. Click on it. On the right, the documentation for the String class is displayed and again, you can scroll through it. You will find a summary of all of the methods. There are many methods, most of which you don't need to know, and when there's one that interests you, you can click on it and get a detailed explanation. You will have lots of practice with that during this lesson.
First off, let's look at a typical method call. As you know, all the way on the left is the object, on which the method is called. Next comes the name of the method. And the values, that we supply to the method, are called the arguments. That's just a technical term. This particular method call is called with the arguments 20 and 0. Let's have a look at another method call, again here is the object, the method name. This particular method call has no arguments, there's just nothing between the two parenthesis. But this method call returns an answer, it returns the number of pixels in the picture. That answer, or as we say, that return value, is then stored in the variable that you see on the left. What about the method call up here? This method call has no return value, it simply, carries out an action, namely to grow the picture.
Now, that we know about arguments and return values, let's look at this method call. Recall the days from method, and then store the return value in a variable. What is the argument? What is the type of the return value?
The argument is birthday, and the return value is int. The argument goes in the parentheses and is used in the days from method. The return value of the days from method is then put into the variable daysOld. daysOld holds int, so the return value must be an int.
Let's have a closer look at how methods are described in javadoc. Here is an example. Before the parenthesis you have the name of the method, in this case pixels. Before the name, you have the type of the return value. In this case, that's int because the pixels method returns the number of pixels in an image as an integer since you can't have half a pixel. Let's look at another example, the grow method. Again, the name is before the parentheses and before that is the return type but in this case, remember the grow method doesn't return anything and we use this special word void to denote that. Void means that nothing is returned. Now this method call has another feature. It describes what kind of arguments to pass. You call this method with two arguments and here you find the types you can grow by any decimal number. It doesn't have to be an integer. Now actually and that's a minor detail, that you don't really need to think about until the next lesson. What you see inside here, the double dw and the double dh are themselves variable declarations. They declare two variables that are called the parameter variables. Like I said, right now you don't yet have to worry about the parameter variables but when you see the word parameters in javadoc, then you'll know where that comes from. Now you know all the technical terms that you need to decipher a javadoc documentation.
I found these Method Descriptions in the javadoc. How many parameters does length have? What is the type of the return value.
It has zero parameters, there's nothing in the parentheses. The return type is int, we can see it here.
How about replace? How many parameters does it have, and what are their types? What is the type of the return value? This last one, print line, isn't from the stream class, it's from the print stream class. How many parameters does it have, what's their type? How many return values does it have?
Replace takes two parameters. The first one is target and the second one is placement. Their types are both string. The type of the return value is before the method right here, and it's also string. Print line takes one parameter. The type of that parmaeter is string, and it doesn't have any return values. The type is void.
Let's have a closer look at constructing objects. This time we'll use a different class. The class called rectangle. In BlueJ I right-click on the class in order to construct objects. Now look closely here. Up here I have two lines that start with the keyword new. Followed by the name of the class. The keyword new is an instruction to make a new object of the class that's written after new. Inside the parenthesis, we put the construction arguments. Now notice that the're actually two of these. Two so called constructors. The first one wants four construction arguments. The second one doesn't want any. Let's use the first one. Here we see the construction arguments described as x, y, width and the height. I'm filling in some values, five, ten, 60 and 90 and when I click OK, the familiar object icon appears. Now as always in BlueJ, I can right click on the object icon to find out what methods there are. For example, the get width method gives me the width and that's the 60 that I just supplied. You might be a little disappointed that the rectangle is not displayed but to display, simply call it straw method. Right-click Draw and here it is in a little window. Let's look at the second constructor, the one with no argument. When I select it, I don't need to supply any argument values and the object is constructed. What rectangle might it be? I can draw it. But nothing seems to show up. Let's investigate. it has width zero. And height zero, not a very useful rectangle but of course I can always grow it. And there it is. At any rate you have now seen that the rectangle class has two ways of constructing objects. One constructure take four arguments, the other none. Let's have a look at it's Javadoc.
Because this project has multiple classes, I have to select the one that I want. And now, I can scroll through in the usual way and see the methods of the rectangle class. But I want to go a little bit above that and here you see a summary of the constructors. There are two constructors, the first one takes no arguments and constructs an empty rectangle. The second one takes four arguments. And I can click on it, and I get the detailed description of what each of the arguments are. To construct objects in a Java program, you also use the new syntax. Let's have a look. Over here, you see a variable whose name is box, whose type is rectangle. And the keyword new tells us to make a new rectangle with these values for the construction. Now you know all the details about construcitng objects.
Now that you've worked with constructors a little bit, let's do an example of constructing some rectangles. We want to initialize the variables box, and box2, with two rectangles of equal dimensions that touch each other at a corner. I'm going to give you a few more specifications. I want box to have a width of 20 and a height of 30. I want box's top left pixel to be at x is 60, and y is 90. And if this is the frist box, I want box2 to touch it at this bottom right corner. Boot up BlueJ and try this for yourself. Then paste the code for the two boxes into the editor that we give you. Don't worry if too much if BlueJ isn't working, you can just the Audacity editor we're providing. And here's a quick hint, if you find that your boxes aren't showing up, it might be because you have to remember to call the draw method.
Before I write any code, I'm going to figure out all of the dimensions and specifications of my rectangles. Box will match the specifications given. So, it'll be at 60, 90 and have a width of 20 and a height of 30. The question asks for the dimensions of both boxes to be the same. So this one will also be 20 wide and 30 tall. I need to figure out where this upper left corner is. It looks like it's 20 to the right from 60, so that should be at 80. And it's also I need to put them into the constructor calls. So, in the BlueJ project, I'll edit the code for rectangle demo. Open editor. And then the main method, I'm going to create two rectangles: Box and Box Two. And then once I've created them, I'm going to draw them. We'll make box a new rectangle. Now, this constructor needs to take an x, a y, a width and a height. X we know is 60, y is 90, the width is 20 and the height is 30. Now for box two, x is 80, y is look like this. Let's compile, and now I'll run my method. And it drew my rectangles, just as I asked for.
The best way to become familiar with objects is to use lots of them. Here, we will look at strings and we will do it in three ways. With BlueJ objects, with Java code, and with another nifty tool called the code pad. In the code pad, as you'll see in a minute, I can type in code and have it executed right away without having to compile anything, or without having to click on the bubbles. The code pad is so nifty that it's a shame that it's hidden, to reveal it, select View and Show Code Pad. And then they make it so small, which is also a shame. Let's make it much, much bigger. In the code pad I can write regular Java statements. Here I declare a variable, here I have a print statement. And as soon as I hit the Enter key, it gets executed. You see a window pops up that has the output. But what's even better, any value that I type in here gets displayed right away. Let me show you. I type river.length, and the answer 11 is displayed as soon as I hit the Enter key. It's important that you don't type a semi-colon because otherwise the code pad thinks that you have a statement like up here. No semicolon tells it that it should immediately print the value of the code that you write. Here I type the name of the variable without a semicolon, and it's printed the string Mississippi. And to the left, I have a little blob that I can drag into the workbench. Here it goes. I drop it into the workbench. Now I'm supposed to give it a name. I'll give it the same name, that the variable has river. And over here I have a familiar BlueJ blob. That I can manipulate in the usual way. I can right click on it, and now the string class has many, many methods, but I want to call length. When I select the length method I get the answer 11. So I can get the same answer in two different ways. Which one is better? It really depends. Sometimes I prefer to use the BlueJ bubbles for quick experimentation, because you can't really make any typos. Sometimes I prefer to use the code pad. Because it's just easier to type in, maybe to copy and paste in, what you want. Both of those are great for experimenting with classes and objects, and to just find out what happens when you call a particular method. You should try them both and see which one you like better. Of course for more hardcore programming. For writing a program that gets repeated over and over again, one wants to write an actual Java class with a main method. In that case, as you know, you right click on the empty space, make a new class, right click, open the editor. And start typing. Then you put your code into the main method. Here I wrote a couple of lines of code that let me compute the length of this string. You compile. You run. And you get the answer. That's more work at first, and it'll pay off when you write a longer program. For short explorations, the object bubbles and the code pad are hard to beat. So go ahead. Fire up BlueJ and work along with Sara to explore the string class and its methods.
Let's look at a few more methods from the string class. This is your chance to try reading some Java doc. If we have a variable river that contains this, what method call would replace all of the i's with x's? Write the method call here. What is the return value? You should put it here. Here's some hint. Look for a link on this page to the javadoc for the replace method. Verify your answer using bluej. And here's an example of a method call, birthday.getMonth.
The method would look like river.replace and the first argument would be i and the second one would be x, the return value would be Mxssxssxppx. Let's look at the javadoc to see why. To find the javadoc for the string class we'll search, and I'm just doing this in Google. So, I'm in the documentation for the string class. You want to scroll down and look for the Method Summaries. Under the method summaries, there are a couple of different options for replace. Let's look at this one. It has a detailed description here, it takes a target and replacement. The target is the things that we want to replace, and the replacement is what we should replace them with. So in our case, the target would be i in quotation marks, and the replacement would be x in quotation marks. We can demo how this works in BlueJ. On the river string, I call replace and I replace i with x. [SOUND], and we got what we expected.
The Trim method is another useful method from the string class. What if we have a String messyString that looks like this, and then we run messystring.trim? What's the return value of messystring.trim? You should go to the API documentation and read it and try to answer, using that.
The answer is about the same as what we started with, except that it's missing the space at the beginning and at the end. And if I actually run the method in blueJ, you can see it right here. Let's look at the documentation. Again, I'm in the string documentation and I'm going to look for the Trim method. It says it returns a copy of the string with leading and trailing white space omitted. This part here is just explaining what we mean by white space, exactly. The white space is usually things that you can't see easily, like a tab or a space.
Let's do one more of these. Manipulating strings is actually something that you'll be doing a lot. What are the return values of these method calls? Remember, our string river has Mississippi. river.toUpperCase(), river.toLowerCase(), and river.toUpperCase().toLowerCase. As a bonus, what's the value of river after all these calls?
River to upper case returns MISSISSIPPI in all caps. River to lower case returns mississippi in all lower case. And river to upper case to lower case returns mississippi, also in all lower case. Because it does the first method call first, and then it does the second method call on the returned value for the first method call. After all these calls, river still contains Mississippi. It doesn't change. None of these methods changed the original string.
In the last exercise that you did with Sarah, something remarkable happened. Here we have a string we call toUpperCase. And then, we look at what's in the variable on which we just invoked the method. And we notice that it does not contain the upper case version. So, calling this method did not modify or as we say, mutate the object. We say that toUpperCase is an accessor method, it leaves the object on which it is called unchanged. Instead, it returns a value and that value is then stored in this variable. The uppercased string is here, the original string is still here. Contrast that with that method call. Here we have a picture and we call the translate method on it. When the method is called, the picture changes. It is moved to a different location. We say the object has been mutated. It is now different than what it was before. And we call the translate method a mutator. So again, an accessor leaves the object on which it operates unchanged, and mutator changes or mutates the object.
Thinking about whether a method is an accessor or a mutator is really helpful when you're trying to decide what a sequence of statements prints. So, let's take this sequence of statements for example. We make a string greeting and fill it with hello. We print out greeting and call replace with arguments h and j. Looks like I forgot a parantheses at the end. And then, we print greeting again. What does this sequence of statements print? Is replace and accessor or a mutator?
The answer is, it print jello on one line, and then hello on the next line. On the second line, when we just print out greeting, we can see that it hasn't changed from the original. We say that it didn't mutate. Instead of modifying the original string, the replace method returns a new one. This would be like if you had a mean cat and you told your cat to be nicer. And instead of becoming nicer, it just gave you a new, nicer cat. That's why we call replace an accessor method, not a mutator.
We'll try another example. How about this sequence of statements? I've now opened up the rectangles project. What does this sequence of statements print? Is translate an accessor or a mutator?.
Let's see what actually got printed. Here's our terminal, and we can see the first number, which was the original X value, is 5. The original width is 60, the next X value is 30, and the next width is 60. Since the X value changed from 5 to 30. We know that translate is a mutator.
Sometimes mutators are useful. But they can be tricky to think about. For example, what does this sequence of statements make? First, we create a variable box of type Rectangle, and put a Rectangle in it. Then, we create another variable of the same type, but I want it to be the same. So, I'm just going to use box. Now, I actually realize I need to get the original box out of the way. So, I'm just going to translate it. So, this would look something like, we would create a rectangle. And then, we create another rectangle that's the same. Then, we translate it out of the way. What is the value of box.getX? What is the value of box2.getX?
The value of box.getX is going to be 105.0 and box box2.getX is also going to be 105.0. This is sort of weird. It looks like we called box.translate 100,
Perhaps, you were surprised by the last problem that you worked with Sarah. In that problem, an object was shared with two variables. Let's have a closer look at what happens in that case. Here, we have an object that's stored in a variable. Now, it's important not to confuse the object which I've drawn here with the variable. In Java, an object variable does not actually contain the object. Instead, it contains information on how to find the object, it contains the location of the object. We draw that location with an arrow and we call it a reference. Now, suppose we make a second variable and copy the first one into the second. In that case, we simply copy this reference into this variable. As you can see now, both the variable box and the variable box2 refer to the same object. Now, suppose we call a mutator on one of the variables. As you can see, the object has changed. And that change is observable both through the variable box and through the variable box2. That's just how object variables work in Java. And it's good to know, because you can then explain how objects work when they're copied. Sarah will practice that with you with another problem.
Hopefully you're beginning to see why modifications to one rectangle variable might affect another rectangle variable. Let's try another example. If I run this code. What happens? Does this code draw a blue rectangle and a red rectangle or just a red rectangle or just a blue rectangle or just a purple rectangle?
The answer is a blue rectangle appears. Let's try it out. Here's the blue rectangle it prints. This is because we made a rectangle. And then, we made a variable box. And in that variable, we put a reference to the rectangle we made. Then, we made another variable, box2. And we copied the value from box in the box2. So, we copied the reference. So now, box2 also refers to the same rectangle. Now, we've set the color of the thing in the box to red. And then, set the color of the thing in the box2 to blue. And then, we draw or fill the thing in box, which has the color blue.
What if, instead of copying rectangles, we copy strings? Again, we create a string greeting and then greeting 2 which is a copy of the string greeting. And now we call greeting2.toUpperCase. After these statements, what's the value of greeting? What's the value of greeting2?
The answer is that both will be "Hello World", but they won't be upper case. Let's draw the diagram. Both variables, greeting and greeting2 point to the same string. But since to upper cause isn't a mutator, the string never changes. Instead of changing the original string to upper case returns a new string with upper case letters. I'm going to tell you a little bit of a secret. There's actually no method that can mutate a string. Some methods return a new different string, but they never modify the original.
Copying rectangles and copying strings seemed to have different results, but they were really the same process. We had two variables pointed at the same object behind the scenes. Let's look at a different kind of copying. I make a variable lucky number which is an int, and I set it to 13. And then for my second lucky number I'm just going to set it to the same thing, and then I'm going to change the second lucky number. After these steps, what's now our lucky number? How about lucky number 2?
The answer is luckyNumber is 13, and luckyNumber2 is 12. Let's draw the diagram again. luckyNumber is an int, so instead of having a reference, it just contains the number itself. So initially, we set it to 13. Then we made luckyNumber2 by copying the value of luckyNumber1. Which isn't a reference this time. It's just 13. So, luckyNumber2 became 13, then we change the value of luckyNumber2. We set it equal to 12 instead of 13. Since this isn't a reference, we just reset it to 12, and that's how we get our answer. Again, ints aren't objects. Strings are objects. Rectangles are objects. Ints are not objects.
You've just worked through a batch of tricky problems with Sarah. And maybe the results of the programs were not always what you expected. That's why it's such a good idea to test your programs to see that they produce the right result. Testing is incredibly important in software engineering. And when testing isn't done right, the results can be quite dramatic. Over here, you see the lift off of a rocket, an Ariane rockets off the European space agency that unfortunately a few seconds afterward explodes in midair. Now what happened here is that the rocket had a device to maintain its position and it actually had two backups. And because of that, the rocket engineers didn't think they had to test it. But both back ups failed for the exact same reason actually and testing really would have been beneficial in this case. So let's learn more about how you can test your own programs. Okay, here we are in BlueJ, and I'm going to write a program that tests the translate method of rectangles. Let's have a look. Here, we construct a rectangle, we call the translate method. We print out what happens to the x coordinate and we also print out what happens to the width of the rectangle. And now for the important part. The important part is that before compiling the program, we also think what should it do? And it is really, really important that you think about that right when you write your test program. Here is a super easy way of doing that. You simply add a print statement that prints what you expect that this program should do. Hmm, what do we expect? Let's see. The x coordinate of the rectangle is at 5, the y coordinate is at 10. And now, we translate it by 25 pixels to the right and 15 pixels down. So we have a 5. Translated by 25 pixels, so we expect that the x coordinate is now 30 pixels, and that's what I'm putting here. What about the width? The width is 60 and moving the rectangle shouldn't change it, so we'll expect this to be 60 again. So this is a good example of a Tester program. We do something. We print the results and we print the expected results. Lets quickly run the program. We have the actual x position of 30 and the expected position of 30. And similarly we have the actual width of 60 at the expected width of 60 so the actual and the expected Matchup. That's great. So, the simple lesson is always print the actual and the expected results. Sarah has an activity where you can write you're own test program and practice this.
Kyle gave us all this rectangle code but why are you so sure that Kyle's code works? Now it's your turn to write a test program for the grill method. If you create a rectangle like this with an upper left corner, at 45, 90 and a width of 60 and a height of 90. Let's say you call it box and you call grow with 20 and 20. So it should grow 20 in this direction, 20 in this direction, 20 in this direction, and 20 in this direction. What are the actual and expected values of x, y width and height? Write a test program that compares those expected values with the actual values.
Before we can write any code, we need to figure out what the expected values are. This green rectangle is what our rectangle grows to. This point should be at 45 minus 20 and 90 minus 20. So our expected value of x, would be 25. And your expected value of y would be 70. The width would be 60 plus 20 on one side, and 20 on the other side, so 100. And the height would be 90 plus 20 at the top and 20 at the bottom, so 130. So in the test program, I would create my new rectangle and I would print out my expected value for x. And remember, this is just a comment. And expected value for y, expected value for width, and the expected value for height. I want to compare these to the actual values. box.getX, gets me the, actual value, of X for box. Box.getY gets the actual value for Y for the box. And I do the same thing for width and heighth. Now I can run my test program. I had a couple of syntax errors, so I just fixed those up, and now I can actually run it. And I printed, 45, 25, 90, 70, 60, 100, 90, and 130. Looks like the actual values don't match my expectations. What went wrong? It looks like I created the rectangle and then printed out the actual and expected values without actually calling grove. And now if I run it again, I get the actual is 70, expected is 70, 100, 100, 130, 130, and 25, 25. That's much better. Based on these test results, I'd say the grow method works about, the way it says it will.
So, it's important to test your code, because you never know the impact it's going to have. You sit down and you write a piece of software for one thing, and someone else might see it a month or year down the road. And think of another awesome way it can be used, and you want to make sure that a code you write doesn't break in other situations. And I think that's one of the things that's awesome about computing, is that the code we write has such a big impact. But in order for it to have a big impact, we need to be very vigilant about making sure that it's good. And we build a good product that other people can then take and do more awesome things with.
Now we've been working a lot with rectangles and you may wonder whether there are shapes you can use, and indeed you can. I'm going to show you know more about the graphics library that you get with this course. It's a simple library, I've created it especially for this course. It's very similar to the standard Java library but it's a bit easier to use. You can find the full documentation on the web. But let's just walk through the basics so you get a feel for what you can do. Here is an example of a silly drawing that you can create. When you look at the drawing, you can see rectangles, lines, circles, and text. You already know about rectangles, so let's move on to the other elements. Let's say you want to draw a line from this point to this one. You need the coordinates of the start and the end. And then you simply construct the line by giving the coordinates to the line constructor. You store the object in a variable. And when you're ready to draw it you call the draw method, just like you would for rectangles. Now let's say if you want to draw a circle or an ellipse. A circle is just an ellipse that's symmetrical. Find the rectangle that fits around the ellipse. Determine its top left corner, its width, and its height. And then construct the ellipse, really in the same way, as you would have constructed, the surrounding rectangle. Finally if you want to show some text, specify the top left corner point, and construct a text object. Simply give the coordinates and the message that you want to display. That, in a nutshell, is our graphics library. Sara has prepared a couple of simple practice problems for you.
We've drawn a lot of boxes today. But they've all been very flat. What if we wanted to make this look more 3-dimensional? I want you to draw this box and I'm going to give you a few specifics about its dimensions. This top left corner should be at 20,30. This width should be 100. This height should be 40. This corner should be at 50,10, and this one should be at 150,50.
Before I can write the code, I need to figure out exactly what each of these corners is, so that I can think about the end points of each of the lines I need to draw are. This line's pretty easy, it goes from 20, 30 to 50, 10. This one's a little bit trickier, this point is at the same height as that one, so it's at 10. And it's 100 to the right from 50. That means that its x value is matching up with this one, so that looks good. This point is 100 over from this one. So, 100 plus 20. And this point, gives us 120, 30. And this point is 40, down from this one. So 120, and 70. So we got that first line. Now the second one. Is from 50, 10 to 150, 10. This line is 120, 30 to 150, 10. This line is top length here, and it gives us the width and the height. So we know how to specify that one. Here's how I wrote the code to draw the crate. There's a rectangle, which is that front face. Top left 20, 30, width 100, height 40. Then there's that leftmost line. 20, 30 to match the point that it starts at and 50,10 to match the point that it ends at. Then I did the same thing with the top line, middle line, the rightmost line, and the bottom one. Then I had to remember to draw each of these lines. And if I run this program, it draws the three dimensional crate that I wanted. Good work if you got that. That was a lot of getting all of the right coordinates in place. But if you did that, you should be pretty familiar with drawing lines now.
So, it turns out that this box that we drew actually belongs to a not so great spy, who labeled it top secret. Can you use text to write top secret starting at this left top corner.
All I had to do was create a text object that starts at 20, 30 and has the text top secret in it and then draw it. Now if I run this program again, it'll draw the box and write top secret.
Earlier you wrote a program to create two rectangles that touch at corners. What happens if you run these four lines as well? Which of these will box end up looking like? How bout box 2? I haven't actually told you enough to figure this out but you can try it in blue jay.
I think the best way to find out, is just to try it. When I run my program, prints out this. It looks like box ended up like this, and box2 ended up like this.
Everything that we've drawn so far was in black. Now, black is a marvelous color, but what if you'd like another one, such as one of these? These colors have predefined names, and when you look here, you can see that every color is a mixture of a red, green, and blue component. Red has only red, and no green and blue. Blue has only blue and no red and green. Yellow has red and green, and no blue. You can make other mixtures, and you'll explore that in the exercises that are going to be coming up right now, let's just stick with red. Let's say we have a rectangle that we want to draw in red. You set the color to the color constant red in this way, and then when you draw it, it shows up in red. Alternatively, you can call the fill method, and then the interior's also drawn in red. Now you know everything about the graphics library to make fancy drawings on your own. Go ahead and do the practice assignments with Sara. And when you're done, maybe you'll be motivated to recreate Udacity train. Or create a fancy drawing of your own and share it with us on the discussion group.
These numbers look pretty mysterious. Let's talk more about colors and what these numbers mean. We left a few predefined colors out, here are the colors, and here are their RGB values, though they're mixed up. Can you match each set of RGB values to its color? You can figure this out whether you remember what magenta means or not. As a reminder to help you in your experimentation, this is how you would write code to color a box magenta. And this is how you would write code to color a box with color a.
The answer is that magenta matches c, yellow matches b, white matches d and cyan matches a. But how did I figure that out? I went into BlueJ and created a rectangle, and filled it. So I got something like this. Then when I set the color, it changed to this sort of red-blue color. Cyan is this sort of green-blue color. I'm pretty sure I know what yellow and white look like, so I'll skip those ones. When I set the color to that color described by a, well, that looks exactly like the cyan that we just saw. And if I set it to color b, that looks like yellow to me. Color c looks like that blue red magenta color. And color d. Well, that's just white. It doesn't show up very well on a white background. If you're curious about this system of marking different colors, you could try making brown or orange. But that's all we'll do with colors for now. You've got a little more practice with graphics and a pretty cool project coming up.
So, one of the most interesting projects I've worked on was actually a project that arose out of personal interests. This was around the time that the Euro I did is I went on to the Euro website and I took a whole bunch of statistics about the teams and the games. And I just took that information and I put it into this piece of software. And it was instantaneously able to make these predictions for me about who was going to win, what players were going to perform the best. And that's not something you or I can do with the naked eye very quickly or accurately. But, it's something that this computer could do very well, very fast. And with only a year and a half of programming background, it was information that I was able to extract.
So I think one of the really unique things about computer programming is that, the first time you run your program, it's not going to work. And you shouldn't expect it to work. And people get really frustrated, because that's not something that they've seen in other places. And so my advice for anyone learning to computer program, whatever point you're at, would be to fail forward. It's about writing code, and running a program, and having it not compile. And not run. And while that can be really, really frustrating, you'll see that bug ten times later and you'll understand why that bug is there. And you'll be faster at it. And in the end, you don't when your program just runs, because you don't fundamentally understand why that happened. And so. Just fell forward and learn from your mistakes and be okay with this kind of incremental process.
Great job. Look at how much you've learned. You now know how to make objects from classes and how to call methods on them to make them do things. >> You've learned how to look up the documentation for classes and methods so you can find out what they can do and how to make them do it. >> Also you've learned how to store objects and variables so that you can recall them when you need them. >> Most importantly you've learned how to combine different objects in order to do more complicated things. >> In the next lesson you will learn how to write your own classes, so you can become a giant that other programmers can stand on.