Programming 101
By Way of Java
Instructor: T. Boutell
Transcript for 10/24/96
Stimulants AnonymousWelcome to the Java programmers' roasteria. A wide variety of stimulating beverages are consumed among the whirring virtual machines.
You say, "well, more people are here than originally signed up."
jkcohen presents Tom with a brightly polished apple.
Tom smiles ever so slightly.
vampyr whispers to j.j, "oh, geez. dig THAT suckup."
You say, "welcome to the second meeting of Programming 101 By Way of Java."
You say, "last week we talked about some theoretical basics, because it is difficult to completely avoid them."
You say, "this week, we are going to look at a short applet, and I am going to explain it line by line."
You say, "your task is to stop me and ask me questions."
You say, "to greatly facilitate this, I have made this applet available on the web, source and all."
You say, "to see the applet in action, open this URL in your java-enabled browser, or give this URL to the 'appletviewer' of the java developer's kit:"
You say, "http://boutell.com/~boutell/class/Calculator.html"
You say, "this applet is a simple calculator, with just a few buttons and a field to type numbers into."
You say, "the source code is at this URL, which your browser will hopefully display as text:"
You say, "http://boutell.com/~boutell/class/Calculator.java"
You say, "I'd like everyone to get a copy of it up in a window, and/or on paper, if at all possible."
You say, "I am referring to the source code, of course."
You say, "the first line:"
You say, "import java.applet.Applet;"
You say, "as we've discussed, java programs use objects of many different classes."
You say, "since there are so many classes, it is important to organize them in a sensible way."
You say, "happily for all of you, java classes are organized exactly like USENET newsgroups."
You say, "they are organized into 'packages' and 'subpackages', with the most general package name coming first."
You say, "it is possible to refer to any class in the standard set of java classes by use of its 'fully qualified name.'"
You say, "the fully qualified name of a class which is a member of the applet package, which in turn is a member of the java package, is java.applet.Applet."
You say, "again, this is a lot like the way USENET newsgroups are named."
You say, "the 'java' package contains all of the classes which are guaranteed to be available in any java implementation."
You say, "the 'sun' classes are also very common in practice, but you can't assume they will be there."
j.j says, "'package' = 'library?'"
You say, "j.j: they serve the same purpose."
j.j says, "thank you."
jkcohen says, "Why are there two applets? Is Applet a member of the class of applets?"
You say, "jon: well, java.applet.Applet is the fully qualified name of the Applet class, including the packages it is part of..."
You say, "jon: these names are used to avoid confusion between classes with the same name..."
You say, "jon: when you 'import' a class, you are saying that you'd like to be able to just call it by the last part of its name in this file."
You say, "so, we could refer to java.applet.Applet throughout the file, but this would be a pain in the butt."
soren says to tom, "You only use the word "Applet" one time in this program. Could you get away with deleting this line and just specifying the full name on line 4?"
You say, "soren: yes, I could."
You say, "soren: it is not unlikely that I would want it again in a more complex applet, though."
jkcohen says, "OK -- so we could call this java.applet.Charles and Charles would be the ordinary name referred to in the code?"
You say, "jon: not quite. java.applet.Applet is actually the superclass -- the class you must extend -- to make an applet."
You say, "let me look at the second line for a moment, and then return to that."
You say, "the second line is:"
You say, "import java.awt.*;"
kristen is already lost. sigh. where does this Applet live?
You say, "kristen: actually, java.applet.Applet is a class file which lives in (on my system) /usr/local/java/lib/java/applet."
You say, "kristen: technically it's in a .zip file that java searches as if it was a folder, but that's the idea."
You say, "kristen: java.applet.Applet is one of the standard classes that comes with all Java systems."
gnat says, "Tom: Having the standard classes is the responsibility of the program you use to view the applet, right?"
You say, "gnat: yes. If they aren't there, it's not Java."
gnat says, "Accept no substitutes. Gotcha. Thanks, Tom."
kristen says, "ah, so can i count on it being in the right place on my ISP, or do i have to install it myself, or what?"
You say, "kristen: it is there in the environment the applet *runs* in. Netscape, or the appletviewer, etc. It is also there in your development environment. It is standard."
kristen says, "aie."
You say, "kristen: let me explain line two and see if that helps."
You say, "line two is this:"
You say, "import java.awt.*;"
You say, "now, Java has a single set of classes to be used for user interface things, like windows and buttons and so forth."
You say, "this set of classes is called the Abstract Window Toolkit (AWT)."
You say, "for convenience, the designers of java placed all of these classes in the same package."
You say, "that package is called java.awt."
You say, "if we want to refer to 'Button' and 'Label' and so on in this file, we could refer to them by their full names (java.awt.Button or java.awt.Label)..."
You say, "or we could cut down on the grief by importing each of them..."
You say, "but instead we use a handy 'wild card', just like in DOS or Unix commands like ls and dir."
You say, "when we write 'import java.awt.*;', we mean, 'let me refer to all of the awt classes by their short names.'"
stevi says, "does it increase the memory requirements of the applet to import the whole package like that?"
You say, "stevi: good question. We are not really 'sucking them in' to the applet..."
You say, "stevi: what we're doing is just telling the *compiler*, which we run only once if we're very lucky, that we want it to try putting 'java.awt.' in front of the name of any class we refer to, and see if that matches a class that actually exists."
stevi nods.
You say, "stevi: what I'm getting at is that we're saving ourselves typing, not doing something physical."
You say, "this way we don't have to type 'java.awt.Button' over and over and over. We can just type 'Button'..."
You say, "and this works fine, as long as we don't have another Button class imported or in our own code."
j.j says, "is there some way of establishing precedence if two packages contain classes with the same name?"
You say, "j.j, to answer your question,"
You say, "j.j, if two packages contain classes with the same name, it is better to import the classes you need individually..."
You say, "j.j, if you need both of those classes that have the same name, refer to them by their complete names. foo.Name and bar.Name."
j.j says, "will it fail to compile if you just didn't know there were two with the same name?"
You say, "j.j: not if you don't actually try to refer to that name, I think."
Tom clarifies some more: packages are there to avoid confusion and let us be precise. 'import' is there to let us say 'actually, I'd rather be a little vague and type a lot less stuff.'
You say, "OK so far? Shall we move on?"
gnat says, "ah, so import doesn't import code, just names."
j.j nods.
gnat nods.
stevi nods.
kristen noodles.
You say, "OK."
You say, "OK. The next line is:"
You say, "public class Calculator extends Applet"
You say, "now, we've seen most of this before. Anyone want to translate that to English, ignoring anything they'd rather not try to explain?"
j.j says, "it is more or less in english already, isn't it? we're creating a new class of type Applet called calculator, and it's public."
j.j says, "whatever that means."
j.j says, "i don't know from public."
Tom nods.
You say, "we are declaring that the class Calculator is 'just like' an Applet, and now we're going to qualify that by explaining what's unique about calculators."
soren says, "a public applet differs from a... private(?) applet how?"
You say, "well, as to 'public' and its relatives..."
You say, "programmers hate it when other people use their code in ways they didn't plan for."
You say, "if I write a class for you, I probably expect you to create new objects (which calls the constructor) and do some things you asked me to support (like describing the object, or painting it on the screen)."
You say, "but I'll probably write some other methods too, which are used by those methods, especially to save typing the same code many times."
You say, "for instance, if you're renting cars, you want people to be able to turn the wheel, press on the accelerator pedal, press on the brake, and so on."
You say, "however, you *don't* want them to rewire the transmission."
You say, "especially if you are *renting* this car to them, and taking care of it is your problem."
You say, "so Java classes, just like material products, have features which are 'not for gefingerpoken.'"
You say, "in Java, if we want the user to be able to 'touch' something, we have to make it 'public'. We can do this with classes, variables, and methods."
You say, "an applet needs to be public, so users can access it."
You say, "so we declare that the class is public, and now it can be used by the outside world."
You say, "now, we did things like this last week, so I'll be brief. These 'Button' lines are declaring variables that will refer to objects of class Button."
kristen can't quite picture where you'd use a private class.
You say, "kristen: if you don't declare a class public, other classes in the same package -- the same file in the simplest case -- can use it."
j.j says, "can or can't?"
You say, "j.j: can. The same package only, though. Other applets cannot."
You say, "kristen: so you could have classes for various smaller parts of your applet, keep them all in one .java file and make only the class derived from Applet public."
Tom had better note that, if you don't explicitly put a file into a package, all the classes in that file are in a 'default' package. This is fine for applets and we don't need to go into how to put classes into packages at this time.
You say, "if there are no questions, I'll move to the next line..."
You say, "Button add;"
You say, "This declares a variable that will refer to a button object. We haven't actually created an object yet; this variable refers to nothing right now (null). We will create the object later."
You say, "Button equals; and Button clear; do the same thing for two more buttons."
soren says to tom, "so these "Button add" things are pointer declarations, and we allocate the actual objects later?"
You say, "soren: yes. They are references."
You say, "TextField results; declares a variable that will refer to a java.awt.TextField object. Text fields are used for simple one-line text entry. This is probably obvious if you have played with the applet."
You say, "float current = 0; is a little different..."
You say, "you may have noticed by now that all classes have capitalized names."
You say, "you might assume that variables to store numbers would be no different from other classes."
You say, "they are different, though, even though this isn't quite elegant."
You say, "one good, simple reason is this:"
You say, "writing Float f; f = new(5); would get really, really tiresome very fast."
You say, "there is a Float class, and it has some useful methods in it, but objects are relatively 'expensive' and slow when you are trying to calculate something..."
You say, "so the types 'float' and 'int' (integer) act more like variables in C and Perl."
kristen wonders how 'new()' works...
You say, "kristen: we'll touch on that more and more as time goes on."
You say, "'float f;' actually does make space for a floating point number right away, and you can assign values directly to it. You don't create an object with new."
You say, "if you are confused about this, you might just remember that 'float' and 'int' act like simple algebra. You can say 'float f = 5 * 5 + 2;' and expect to get 27, as you would have if you were careful in high school."
You say, "now, the next line declares a method:"
You say, "public void init()"
You say, "I should mention that this method has a special meaning in an applet."
You say, "when a web browser loads an applet, what it does is load the applet from the net or the hard drive, create it with new(), and then wait until it's actually ready for that applet to do things in the web page."
You say, "when the browser is ready for the applet to do real work, it lets it know by calling java.applet.Applet.init() on the applet object it has created."
You say, "the java.applet.Applet class is the class we are extending, so when the browser loads our applet and calls that method, it gets our version here in the Calculator class."
You say, "this is an important feature of java. If you extend a class that contains a method, and provide a replacement for that method, your version gets called instead. This lets you change how a class behaves in your version. It also means you can have methods that are just 'placeholders', and write the real versions in many different subclasses."
You say, "java does this a lot. Every applet you write will be a 'more specialized' version of java.applet.Applet, replacing various parts of that class with methods that do something interesting."
You say, "any questions so far?"
jkcohen doesn't understand what methods get *replaced* in this applet.
You say, "jon: most of the methods in this applet are replacements for standard methods; in fact, all of the public ones are, so the browser can call them..."
You say, "jon: the way to find out is to open up the JDK documentation, and go look at the documentation for java.applet.Applet."
You say, "jon: a lot of these methods are actually replacing methods declared by the parent classes of Applet itself, but we don't have to think that hard just now."
jkcohen duly makes a note to RTFM.
You say, "now, here's the EXECUTIVE SUMMARY, otherwise known as the practical, non-confusing explanation:"
j.j blinks.
You say, "'public void init() is a lot like a constructor. When you write an applet, write a public void init() method instead of a constructor and you won't go wrong.'"
jsam smiles.
jkcohen says, "void means you don't get a variable back?"
You say, "jon: yes. No return value, so you can't say x = init(); and expect x to get a meaningful value."
You say, "now, let's look at the code of the init method."
You say, "add = new Button("+");"
You say, "here we actually create a button. We do this by using the 'new' keyword, which tells Java to do a little magic and make an object, then call the constructor for the appropriate class..."
You say, "the string argument "+" gets passed as a String object to the constructor of Button. If you look at the documentation for java.awt.Button, you'll see that a constructor taking a String is provided."
kristen neat.
You say, "this is neat: we don't have to do any work here because a handy Button class comes with Java. We just ask it to make one."
You say, "now, let's look at the next line:"
You say, "add(add);"
You say, "I apologize for giving a method and a variable the same name."
You say, "the 'add()' method is one of the standard methods of an applet. Actually, it comes from java.awt.Container, which is one of the ancestors of applet. Any component that might contain others, like a dialog box or an applet, is a descendant of Container."
You say, "when we first create the button, we haven't given it a place to live, and it is sad and lonely."
You say, "when we add() the button, we are asking the applet to provide accommodations."
soren says, "can you specify location?"
You say, "java has a lot of ways of deciding how to arrange things you add() on the screen. You can pick and choose among them. Happily the default is a simple layout that meets our needs here."
Tom pauses for questions and hair-tearing.
j.j says, "so, add(add) says to put our button on the screen? and if we wanted to put it someplace special we would add something to add(add) like ... ?"
kristen says, "add, uh, lays things out in a bigger gray window?"
You say, "kristen: yes -- it lays things out in a container -- the applet is considered an acceptable container, so if we call add() it'll just lay it out in the main applet window."
You say, "note that we add buttons for 'equals' and 'clear' in the same way."
You say, "moving down a few lines..."
You say, "result = new TextField(20);"
You say, "in this line, we create a TextField object. TextField offers a few constructors too; one of them accepts the number of characters to make space for in the text field."
You say, "a TextField is a subclass of Component, just like a Button is, and you can add() it in the same way. A lot of things in java are designed like that."
You say, "now that the init() method has done its work, we have a complete applet, which appears on the screen when an HTML page that refers to it is viewed."
You say, "of course, it doesn't do anything useful yet. To do something useful, an applet has to respond to things that happen in its environment. These things are called events."
stevi starts to feel reckless with her new empowerment.
You say, "heh."
You say, "let's look at the next line:"
kristen claps. this is a neat example.
You say, "public boolean action(Event event, Object arg)"
You say, "in java, there are several kinds of events. java.awt.Component has a method that gets called for each kind."
You say, "to make your applet do something interesting, you replace the methods for the events you care about."
You say, "generally, if an object doesn't do anything with an event, it gets sent to the container instead. This is handy for us..."
soren says, "'the container'?"
You say, "soren: whatever container we add()ed the object to."
You say, "soren: in our case, the applet. We called add() for each of our components in the init() method."
You say, "now, when a button is clicked on, this causes an 'action' event."
You say, "'action' is just an arbitrarily chosen name for this kind of event. There are others, like mouseDown and mouseUp and so on."
You say, "when an 'action' event happens, Java makes sure the java.awt.Component.action() method is called. We can replace this in our applets, and that's what I've done here."
j.j says, "so, you didn't pick the name "action," it's an existing method?"
You say, "j.j: yes."
You say, "j.j: there are a few of these. action, mouseDown, etc. java.awt.Component documentation lists them."
j.j says, "gotcha. will look them up."
j.j says, "thanks."
You say, "if java.awt.Component.action() returns false, the awt takes that event and asks the container if it's interested. That's why this method returns a boolean (true or false) value: to say whether we 'ate' the event, or if it should be passed on to the container around us."
You say, "the 'standard' version of java.awt.Component.action() just returns false. This is cool, because it means a button, which doesn't replace that method, will pass its events up to us."
stevi is a little lost. "If you click the button, it returns 'false?'"
You say, "stevi: that was a bit too much detail... how about this: when a button is clicked, the action() method of the container will get called."
You say, "stevi: I was explaining how that is achieved, but that's not really critical."
stevi nods.
You say, "now, let me move on a line in a way that will hopefully clarify what's happening:"
You say, "if (event.target == add) {"
You say, "note that one of the arguments to this method is an object of the Event class."
You say, "the Event class has quite a few members, including 'Object target'."
You say, "okay. The 'target' of an event is the component that the event began life in. If this action event occurred because the user clicked on a button, then the 'target' will be equal to that Button object."
You say, "this line of code compares the target to our 'add' variable. If they are the same, we know this came from the add button."
You say, "questions at this point?"
j.j says, "i'm following!" with some surprise.
stevi is still stuck at the (Event event, Object arg)
You say, "stevi: okay..."
j.j says, "Event and Object are classes in java.awt.*"
You say, "stevi: that part declares what kind of arguments this method will take."
You say, "stevi: we are saying that this method will accept an Event object and an Object object (any old object!)."
You say, "stevi: the environment you run the applet in -- a web browser or another java tool -- handles events and passes them on to your applet."
Tom notes that the ultimate ancestor of *any* class is Object. So you can pass around 'generic' references to objects. If you don't quite follow that now, it's OK.
stevi just didn't know where the 'arg' came from.
kristen nod nod.
kristen says, "arg confuses me too."
You say, "stevi and kristen: oh, the 'arg' part!"
You say, "Okay. Since we are replacing a method in the Applet class, we have to accept exactly the same arguments that the original did..."
You say, "although we don't use 'arg' in our version, it is there to match the original method we are replacing, in java.awt.Component, which applet is descended from."
stevi says, "oh. so it's Just Good Code."
You say, "stevi: well, you can have two methods with the same name, but different argument types, and it's OK as long as the compiler can tell them apart."
You say, "stevi: so if we had different arguments the compiler would assume this was *really* different and not use it as a 'replacement'."
You say, "stevi: but the 'good code' explanation is fine for now if you like."
stevi says, "ahhh. i think i see now. 'yo, compiler, i REALLY mean for this to replace action.'"
j.j says, "question."
j.j says, "the original class has arguments of Event and Object, but do we have to call them event and arg?"
j.j says, "or can we name them anything?"
You say, "j.j: you can name them anything. Same types in the same order. That's what matters."
soren says, "what _could_ that argument be?"
You say, "soren: it depends on the event. It's a little redundant, in my very humble opinion. In action(), it's usually a String object with the name of the button, but getting it out of 'arg' is actually more confusing than the way I did it."
j.j says, "cool."
kristen says, "but it doesn't get confused if it only gets an Event and no Object?"
You say, "kristen: java actually *does* provide an 'arg', but we didn't choose to use it."
You say, "kristen: you don't have to use call waiting to get some use out of your phone."
Tom hmmms. "We're out of time for this week. Let's continue with Q&A."
kristen says, "uh, in this particular instance, what is the Object? that's what i am confused on..."
You say, "kristen: well, an 'Object' could legally be any subclass of Object, just as we get our applet into Netscape by saying it's an 'Applet', and Netscape calls methods that Applet declares and we provide more useful versions, etc..."
kristen says, "aie, aie, tom, more confusion."
kristen says, "i am just confused because i see two arguments in the action method but i can only figure what the Event is (mouseclick, whatever) and not hte other one."
You say, "kristen: okay."
You say, "kristen: I think what's bothering you is that I didn't *use* arg, so I didn't think I had to explain it."
kristen says, "you are not using it, does that mean there is no arg being passed at all?"
You say, "kristen: nope, as it happens..."
You say, "kristen: if the action event came from a button, then the browser will pass the name of the button as 'arg'..."
You say, "kristen: depending where the action event came from it could be something else, so it's declared as a generic Object..."
You say, "kristen: just for you, here's how we would actually use it if we really wanted to:"
kristen says, "aaaah."
You say, "kristen: String name = (String) arg;"
You say, "kristen: if (arg.equals("clear")) { do something useful, etc. }"
You say, "kristen: that (String) is a bold assertion on our part. It says: 'this object is a String, dammit. If I'm wrong, stop this applet RIGHT NOW.' And the browser will, if you're wrong."
You say, "kristen: you don't have to get that now, but it's all the cooler if you do."
stevi says, "so although we don't see it in the code, when we click on an Object, it passes its name as 'arg' to the applet?"
stevi says, "or arg passes its name, or however you properly express the idea..."
kristen seconds stevi... the object in question is the button pressed?
You say, "stevi: if it's a Button, arg refers to a String object containing the label of the button. Theoretically some other component might send another type of object as arg. It is indeed a bit confusing, and not my favorite way of doing events."
j.j says, "ok, i have two questions."
j.j says, "first one: the init method versus a constructor?"
j.j says, "last week you said, 'It is good practice to have constructors in all classes...'"
j.j says, "and that the constructor has the same name as the class."
j.j says, "but is it really better to just create an init method?"
You say, "j.j: I'll stonewall and be totally practical on this one, without providing a good explanation..."
You say, "j.j: anything you derive from java.applet.Applet should have an init() method. Any other class you create should use constructors."
j.j says, "oh! that's more than good enough for me."
j.j writes that down.
j.j says, "ok, my second question: is there any easy way to tell whats an Official Java Word and what's a made up name, or is that something you just have to know?"
You say, "j.j: there aren't many more that you don't know at this point, not that are used with any regularity. There are lots of Official Java Classes, but you can find them all in the java.* package."
j.j will peruse the java.* package at her leisure.
j.j says, "thanks, tom! you're the scrum-dilly-bestest."
j.j does a happy "java is FUN" dance.
stevi fehs to j.j who has just put her in the mood for dairy queen.
Tom laughs.
stevi notes that trying to add letters in the Calculator makes it choke.
You say, "stevi: hee."
You say, "well, it doesn't produce a very good error message, anyway."
j.j says, "how does java.awt.* size the buttons?"
You say, "j.j: actually, at Marc Andreesen's insistence, java uses 'real' native controls from Windows or the Mac or whatever. But at any rate, there's code in the implementation of Button that calls some more of those standard Component methods to do things like asserting its minimum size, once you pass the label to the constructor."
vampyr sips a mocha.
j.j says, "ah. makes sense."
j.j says, "right, now i remember. we don't have any real control over the size of things, that's up to the browser. and that's why the buttons and text were so tiny when i played with your java mud client on a high res machine."
You say, "j.j: yes. Actually, I can say what font size to use, and ask how big the screen is. Things are less restrictive than, say, HTML layout."
You say, "You can make your own components, by extending java.awt.Canvas which is a subclass designed for that use. If you do that, then you can call resize() to state your minimum size and add() will respect that, and so on. It's all pretty neat and useful."
vampyr says to Tom, "is there any particular reason why you don't call 'String text = result.getText();' before the various if statements in the action method, so that number is snarfed on any given action? Wouldn't that save a few lines?"
"vampyr: that would be a reasonable thing to do, since there's no harm in doing that even if it's not required for this button."
You say, "vampyr: adding subtraction, et cetera, is a pretty reasonable thing to attempt, too."
j.j says, "you know, i think i have a real conceptual problem with the difference between classes and objects."
j.j says, "i have written down here, "target is an object in class Event." ok. ok ok ok. hmm."
j.j says, "ok, tom. cool."
You say, "j.j: remember the dog example?"
j.j says slowly, "yyyyyes."
You say, "j.j: we had classes called 'ears' and 'tail' which were not 'like' dogs; they were descriptions of *parts* of dogs."
You say, "j.j: and we just declared variables referring to objects of those classes inside the dog class to represent that."
You say, "j.j: this is just like those Button objects in the Calculator class. A Calculator has some Buttons in it. That doesn't mean the class of Button wouldn't exist without the class of Calculator."
j.j says, "objects of various classes can be members in other classes?"
You say, "a reference to any class at all can appear in any other class."
j.j scratches this in her brane with a rusty coathook.
You say, "heck, a Dog class can have a member variable like this:"
You say, "Dog parent;"
j.j says, "parent is an object of class dog?"
j.j says, "and parent is a member of class dog?"
j.j hyperventilates.
j.j says, "whoa, i just got the weirdest sensation of de ja vous. ouch, there it is again."
You say, "j.j: hee. Almost: variables in Java are *references.* They tell us where to find an object; they aren't complete copies of the object."
vampyr says, "eep. try this with your calculator: 2 + 2 + = + 2 ="
You say, "vampyr: hee, yes, I know that + = + does weird things. Turns out a typical pocket calculator does a number of subtle things to make sure it behaves 'reasonably.' Feel free to fix it."
j.j says, "which bit is the variable? parent?"
You say, "j.j: yes, parent is the variable. 'Dog' is there on that line to say what kind of object it will refer to."
You say, "j.j: there's a variable in your head called 'Dad' where you've scribbled down his address. That doesn't mean your ENTIRE FATHER is SITTING ON YOUR BRAINPAN."
j.j feels like SOMEONE is sitting on her branepan for sure.
j.j says, "ok. well, i'll go too and let you have some peace. thanks for your patience, tom."
vampyr says, "it doesn't help that i need to kill msie every time i reload."
You say, "vampyr: use appletviewer."
You say, "vampyr: it works even over the net."
You say, "vampyr: appletviewer is a web browser that only knows three or four tags, all having to do with applets."
Next | Up to the Index
Follow us on Twitter | Contact Us
Copyright 1994-2012 Boutell.Com, Inc. All Rights Reserved.
