310 likes | 386 Views
The Object-Oriented REvoluCiÓn. Chapter 2. Keeping Track of Things. Naturally, as we move through a program we’re going to want the computer to remember things for us.
E N D
The Object-Oriented REvoluCiÓn Chapter 2
Keeping Track of Things • Naturally, as we move through a program we’re going to want the computer to remember things for us. • Remember, the goal is to make the computer do things it’s good at, and computers are pretty good at remembering things exactly. • To do that, we have to make a bucket to store the information. • That bucket is called a variable. • A variable has two things that we care about directly: a name, and some contents.
What’s in a Name? A lot, actually. • The name of a variable(a.k.a. its identifier) can contain any number of letters, digits, and the underscore character _ . You can’t use other characters, including spaces. It must start with a letter, but then you can name it whatever you want… • A WARNING: Choose your names carefully, young padawan.
A few basic rules, though: • You can’t use a special word that is already reserved for use by the Java language, e.g. break, for, assert, else. • By convention they should be written in Camel Case– meaning that the first letter is lower case, but any additional words are capitalized inside the identifier. For example: myFirstProgram, or goBlue, notAhronheimRulez, orComputerScience4Life. • Remember, an identifier is supposed to identify what the variable stores, so pick a name that is immediately understandable. If it stores a student’s age, call it studentAge, not pamplemousse. • Don’t forget, Java is case-sensitive. If you goof up the name, Java won’t know what you’re talking about.
A Cautionary tale • True story: • A student in one of my classes who was working on a very tricky program that you will have to do eventually, chose his names rather lazily. • Among his names: aHasMethods, aHasMethods2, hasMethods. • All these things were completely different and mostly unrelated. Some weren’t even variables. • Guess how well that program worked? • …Yeah. I had to spend over an hour, just trying to understand what was going on before I could even start trying to figure out what the actual problem was. • Don’t do that. Okay? Just don’t.
Anatomy of a Variable • Every variable in Java has a type. • This type tells Java how much space to set aside for it, as well as what operations we should be able to perform on it. • Types can be int(egers), float(ing point), char(acter), String (of characters), and many others. • Because variables can be so different, we need to give Java a “heads-up” that we need a variable, and it needs to be of a specific type. • This is called a variable declaration. • You cannot use a variable until it has been declared.
Declaring a Variable • A variable declaration is simply a statement of the type, followed by the desired identifier: • intmyNumber; • String studentName; • long numOfArtichokes; • In General: • varTypevarIdentifier; • This tells Java to grab us the appropriate amount of memory and label it with our chosen identifier. • However, the buckets are all empty at present. We have to fill them up with values before we can actually use them.
This is not the equal sign • What do we do now that we have an empty bucket? Put something in it! • We assign a value to a variable using a very special character that looks a lot like the equal sign, but don’t be fooled! • The symbol is called the “Assignment Operator”. • It looks like = • It has one job, and one job only: Take whatever is on the right side of itself, and try to stuff it into whatever is on the left side. • It isn’t an indication of equality, it is an ENFORCER or equality. If the two sides aren’t already equal, they’re about to be… OR ELSE!
Remember: = is Not an Equals Sign • As long as you keep the idea in your mind of stuffing the right side into the left side, assignment statements start pretty simply: • myNum = 15; • studentName = “Kid, Billy The”; • numOfArtichokes = 21238795864; • After each of these lines executes, the variable now has the same value as you just gave it. Until you change it or the current bit of your program finishes, Java will remember the value for you.
Two birds with one line of code • It is totally legal to merge a declaration with an assignment, for example: • char goodGrade = ‘A’; • intscoreMax = 100; • You don’t need to do that, but make sure that you give a variable a starting value before you use it. • Some variables will have a default values, others won’t. • If you accidentally use an uninitialized variable, either nothing could happen, or YOUR WHOLE PROGRAM COULD CRASH. • Be careful!
Let’s look at an example • A very informative one.
What are the possible types? • Java defines 8 primitive types of variable. A variable that contains a primitive is simply a “dumb bucket.” It holds the variable and will produce it on demand, and that’s all. They fall into these categories: • Some flavor of integer (from smallest range to largest): • byte (8-bit integer, -128 to 127) • short (16-bit integer, -32768 to 32767) • int (32-bit integer -2147483648 to 2147483648) • long(64-bit integer, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807) • Floating point (decimal) number: • float (single precision, from about 1.4E-45 to 3.4E38) • double (double precision, from about 4.9E-324 to 1.8E308) • boolean (True/False) • char (Single character)
That’s all? • Yep. • Don’t worry, you can represent many, many things beyond primitive values, but they become something beyond dumb buckets. They become…. • <pause for dramatic effect>
Classes and Objects • An Object is a structured box that contains two parts: data that is stored and operated upon, and “methods” which are like mini-programs that the Object can use to process data. • Objects are self-contained, and if programmed properly, should only be accessible to outsiders by a limited set of these methods. The inside of the box and its structure remain hidden from anyone using the Object. • Rather than handling the data directly as you would with a primitive, you have to manipulate the Object through the methods that it provides.
Isn’t that unnecessarily annoying? • You might think that, but think again. • Let’s chat a moment about Object Oriented Programming.
Creating an Object • The structure of an Object has to come from somewhere, and in Java, that structure comes from its Class. • A Class defines the way an Object stores data, and its behavior, including the Object’s methods. • Think of it like this:
Blueprints vs. Houses • Home builders use blueprints to determine how a house will be built. What are the sizes of the rooms? What materials will I need to make the roof? How will it be heated and cooled? Which way should the front door open? • One blueprint is all that’s needed for many houses, and it defines what all the houses will look like. • That’s not the same thing as a House! Ever try to close the door on a blueprint to keep the cold out? • A house is a real, tangible thing. It isn’t just a design, it is actually crafted from wood and metal. It has a unique address. Even houses from the same blueprint can be painted different colors. • Classes are like Blueprints while Objects are like the houses that the blueprint is used to create.
Classes vs. Objects Class Object Eric Solarz Chris Dulzo’s copy of Big Java by Cay Horstmann • Student • Student at Catholic Central • APCS Student at Catholic Central • Book • APCS Book • Big Java, 5th Edition by Cay Horstmann, Sold through Amazon.com in Late August to an APCS Student who attends Detroit Catholic Central High School, Novi, MI, 48374.
More examples • In general, we say that any Object is an instanceof the class that it belongs to. For example: • My specific book that I hold in my hand is an instance of the class “Textbook.” • My 2006 Honda Civic LE 4-Door in the CC parking lot right now is an instance of class “Car.” • Alec McCarthy is an instance of class “Student”. • You get the idea!
In practice • To keep it simple, let’s look at the String class first. • To declare a String variable you still use the format varTypevarName. • String studentName=“Little Jimmy”; • You may notice that unlike the primitive types, String is very conspicuously capitalized. That’s on purpose. • You should capitalize ALL CLASS NAMES. That’s an easy way to let people know what is and is not a class! • Knowing that, what do you expect the difference to be between the following variables? • intmyNum = 10; • Integer myNum = 10;
Methods • Objects can have one or more methods associated with them. You can call one of these methods by using the following format: • varName.method(parameters); • varName is the Object that the method belongs to, and parameters are any necessary pieces of information that the method needs to do its job. (More on this in a sec) • For example: • intnameLength = studentName.length(); • or: • System.out.println(studentName);
Parameters • Before you can call a method, you may need to supply it with extra information it needs to run. • This information comes in two forms: explicit and implicit parameters.
Implicit Parameters • The implicit parameter is the Object whose method is being called. So in studentName.length(); studentNameis the implicit parameter. • The Object is always passed automatically as the implicit parameter, but you still need to be aware of it! • There can be no more than one implicit parameter.
Explicit Parameters • Explicit parameters are extra things that have to be passed to the method for it to run. These are contained in the parentheses that follow every method call. You have to match the order and type of each parameter exactly! studentNameis the EXPLICIT parameter in System.out.println(studentName); • There can be any number of explicit parameters, but it is the job of the program calling the method to provide them, or else the program won’t compile. • Once the method is called, your program comes to a halt and waits while the computer jumps to the method you asked it to run.
Returning • Once the method completes, the computer returns to where it left off in your code, carrying with it any results that the method generated. For example: • intnameLength = studentName.length(); • The length() method of the String class returns the number of characters in the String as an int. • In other words, the length() method of the String class method returns a value of type int. • Keeping track of the return type of a method is very important, since unless you have a variable of the correct type to “catch” the return value, it is lost. • Many methods will have no return type at all, like System.out.println in which case you don’t need to do anything beyond calling the method.
Overloading • One of the up sides of needing to match the types of explicit parameters exactly is that Java can differentiate between two methods with the same name by checking to see what types of parameters it is being passed. • These are called “Overloaded methods” and they’re both legal and extremely useful! • For example, the System.out.println is massively overloaded! • The java PrintStream class that System.out belongs to defines 10println methods, each with a different set of parameters. • This means that you can System.out.printlnpretty much anything and Java won’t complain! It just uses the version of println that matches the parameters it was given.
Making Objects • To make an instance of a class, you declare the variable to hold it normally, but outside of a few special cases you can’t just give it a value directly. • The book uses the example of the Rectangle class, so we will, too! • A Rectangle has several different values to keep track of, and they all need to be set before we can use it. x and y positions, as well as length and width all need to be set when we create the Object. • We do this using a very special kind of method called a constructor.
Calling a Constructor • To create a new Object, you need a variable of the correct type to store it in, then you need to call the constructor using the reserved word new. • Assuming you already declared a variable of the appropriate type: • varName = new ClassName(parameters); • A specific example: • Rectangle box = new Rectangle(5, 5, 10, 10);
Facts about Constructors • Constructors ALWAYS have the same name as the class they construct. (The Rectangle constructor is called Rectangle and the Rutabaga constructor is called Rutabaga). • Constructors ALWAYS have the return value of their class type. (The Rectangle constructor returns a Rectangle and the Rutabaga constructor returns a Rutabaga). • Constructors can ONLY be called after the reserved word new. • Constructors can be overloaded like any other method, and often are. • It’s common for a class to provide a “default constructor” that has no explicit parameters. The constructor creates the object using predetermined values defined by the original programmer.
Accessors and Mutators • These are special kinds of methods that allow us to retrieve information about an Object (accessor), or change information in them(mutator). • If an Object is well designed, you should only be able to access specific information about an Object through these methods. • Accessors often start with the word “get” and will always return a value of some type. For example the Rectangle class has a getHeight() method that returns a value of type double. • Mutators often start with the word “set” and generally require a parameter. Rectangle has the setSize(int height, int width) method.
Does he ever stop talking? • Let’s mess around for a bit with actual code to see what all of this stuff actually means in practice. • And yes, I do stop talking on occasion, Mr. Title Bar. • … • You big meanie.