|
~ Java for Web Page Production ~ Session 2 - Fundamentals of Programming and Object- Orientation |
We have talked about some of the aims and objectives of Java, and looked at a sample of what it can do using the simple QuickCup IDE.
In this session, we will be looking at some of the fundamentals of programming in Java, including a look at some of principles of object-orientation.
In the second half of the session, we will be applying some of these principles by making amendments to the TextBurst Java applet, introduced in the previous session.
In Session 1, we covered:
Introduction to the course tutor
Registration
What is a program?
A brief history of computer languages
A brief history of Java
What is an Applet
How Applets can spice up your web pages, and a look at comparable technologies
How Java is used by your browser, and an introduction to the JVM and Java Plug-In
The Java SDK (Software Development Kit)
Introduction to IDEs (Integrated Development Environments) and QuickCup
Introduction to the basic JDK tools
Text Editors
Creating your first applet - TextBurst
The QuickCup toolbar
Compiling an applet
Testing an applet
Changing the parameters to the applet from the web page
In session 2, we will be looking at:-
Variables & Arrays; Numbers & Strings
What are classes and objects?
About methods and attributes
Inheritance and the Applet
Scope
~~~ break ~~~
Amending the TextBurst sample to alter its speed via the HTML page
Amending the TextBurst sample to add a second JLabel
Standard documentation - where to load useful Java SDK documentation from, and how to reference it directly from the world-wide-web.
Summary and Further sources
Variables & Arrays; Numbers & Strings
One of the most important fundamentals in computer programming is the concept of variables.
Put simply, a variable is a storage space - a bit like a folder in which you place information for a particular purpose so that you can retrieve it later, when it is needed. You may also wish to change what is in the folder from time to time to keep the information up-to date.
For example, if your folder contained information about the current share price of your latest investment, in pence sterling, you might want to look at it from time-to-time, to remind yourself what the share price was when you last checked it. However, this information will become quickly out-of-date, so you may have to check the Financial Times to check what the current share price is. You can then replace the price recorded in the folder with the current price.
So a variable stores exactly one piece of information temporarily so you can use it for later use, whereupon you may wish to discard the information, keep it just-in-case, or perhaps replace it with more up-to-date information.
A peculiarity of variables is that because they are stored in the computer's memory for quick retrieval, if your program finishes, or the computer loses its power for whatever reason, the contents of the variables are lost.
For this reason, variables are usually used as temporary storage whilst performing calculations, or performing the tasks of a program. If you wish to store the information more permanently, you have to think about which medium you wish to use to store the data, and whether you wish to retrieve it again within your program. Possible strategies include storing to disk as a text file, storing to the user's machine as a cookie, storing the data to a database, sending an email containing the information, or passing the information to a server using a Remote Method Invocation (RMI) call.
Variables are also called attributes when applied to object-oriented programming. You'll see why later.
So let's take a simple example. Let's say we create a box called "myInteger" into which we store - well, nothing for the moment.
This variable is an integer. This means simply that the box can store a whole number, with no fractions. Computers work much faster with integers, so if you can work with them, its best to do so.
The alternative is a decimal number which can hold decimal places (e.g. 1.23, 3.1415926535, and even 1.0). Note the last example seems like it should be an integer. In fact, decimal numbers can also include whole numbers, but not vice versa. This makes sense, if you think of currency as being decimals to two decimal places - e.g. 1.23 means one pound and twenty-three pence, and 1.00 means one pound. Note that decimals are know as reals in computers, and the accuracy to which they store numbers depends on the amount of memory the computer takes to store the number - it takes four bytes to store a float and eight to store a double.
Back
to our example. We have a variable called "myInteger" which holds a
whole number, but at the moment, we've not put anything into the box.
To declare the integer variable in a java program, we would type the following:-
int myInteger;
The int part states that the variable is to be an integer (whole number). The myInteger part gives the variable (box) a name. The semi-colon (;) ends the declaration so that java knows to move onto the next instruction.
If
we wanted to put something (say the number 5) into the box when we declare the
variable, we would change the above form as follows:-
int myInteger = 5;
So, we simply put an equals (=) sign after the variable name, followed by the value we wish to place into the variable (or box) - the semi-colon then is placed after that value instead of after the variable name. Our box would look something like the diagram on the left.
Alternatively, we could leave the box blank until we need to fill it later in the program, as follows:-
int myInteger;
...
myInteger = 5;
In this case, myInteger is declared as an integer with nothing in it. A number of instructions are performed as denoted by the (...), and then a further instruction states that myInteger should be set to 5. This is given by stating the variable name, placing an equals after it, and stating what should be placed in the box. Then, of course, the obligatory semi-colon (;) to show the end of the instruction. You can read this instruction in your mind as "myInteger becomes five".
What about Strings, then?
Strings are simply pieces of text rather than numbers - for example, "Hello World" is a common starting point when starting to learn programming.
So why are they called Strings? Well, the term comes from the concept of a "String of characters" used in many programming languages prior to Java to represent textual information. Many languages (including Java) have a type of variable that will store a single character (e.g. A, a, 3, %, and other single symbols) - in java the type is char. A String of characters - i.e. a number of characters joined together - makes a more useful bit of text - e.g. an English sentence. Thus the term 'String'.
So how do we declare a String in Java. Well, for starters, have you noticed that every time I mention the word String, i've been capitalizing it? This isn't bad grammar, but how you need to define it in Java.
Java is known as a case-sensitive language. This means that it notices the difference, and is exceptionally (and annoyingly) fussy between upper and lower case letters. Somebody made the decision that this was a good idea. Just remember, it wasn't me.
This
means that when you declare your String variable, you have to do it as follows:-
String helloString;
or if you wish to put something into the variable at the same time as declaring it,
String helloString = "Hello World!";
Notice the double-quotes around the contents of the variable. These are not put into the variable with the string of characters. Rather, these are used to show where the string starts and stops. You must always remember to start the string with a quote and terminate it with another, otherwise the Java Compiler gets confused, and starts giving you error messages relating to an unclosed string literal followed by thousands of other seemingly unrelated errors that have been caused by making this simple typo.
You can, of course, declare the variable in one part of your program, and fill it in later, as with the example with the integer variable:-
String helloString;
...
helloString = "Hello World!";
What are Arrays?
One of the rules of a variable is that it can only hold one item at a time. Thus, if we take the example of our integer variable, first we had nothing in it, and then we had 5 in it. If we now placed, say, the number 6 in it, then we would effectively lose the number 5, and it would be replaced with the number 6.
So, if we wanted to store multiple versions of the same item, we're in trouble.
Another example. Let's say we want to store a list of people attending the Java for Web Page Production course in a list. We would need to set up a separate variable for each possible course attendee. As we haven't a clue how many will turn up in advance, this could pose a problem. Even if we did know that the maximum number who could attend was eighteen (18), that's still a lot of typing.
So we use arrays. These are simply variables that contain multiple boxes per variable - an array of boxes.
For example, lets say we wish to declare a course attendee list as an array of Strings, one String per Person's name. We would declare our list as follows:-
String courseList[];
Adding the square brackets to the end of the variable name simply states that the variable can now be used to hold a list of Strings rather than just a single string. Of course, at this point we have no idea how long the list is going to be.
If we wanted to fill in the course list when we declare the variable, we would do this:-
String courseList[] = { "Simon", "Bob", "Julie" };
The curly braces show the beginning and end of the list of array values, and is used for any type of array. Each item in the array (here there are three) is separated by a comma (,). What may come as a surprise is that once you have decided how long the array is going to be (i.e. how many Strings will be in the list), the array is fixed at that size. There are various ways of getting around this - including avoiding arrays altogether - but we'll leave that to another time.
So what if you wanted to define an array, and fill in the array with a list of people later in the program? Here's how:-
String CourseList[];
...
CourseList = new String[3];
CourseList[0]:="Simon"; CourseList[1]:="Bob"; CourseList[2]:="Julie";
A
few things to notice about this example. First of all, before using the array,
it has to be declared with the first line, and then later, it has to be created.
The part of the creation line that says new String[3] implies that a new array of three Strings is being created, and the left hand side of this CourseList = says that this new array will be given to the previously defined (but uncreated) String array, CourseList.
Finally, the last line has three instructions on it to place the values in the three boxes within the array variable named CourseList. Note that the first box is given the number 0, the second the number 1, and the third the number 2. This is a common strategy with many programming languages. It often saves the programmer having to type a -1 when performing loops, but actually makes everything a bit more confusing. Again, not my choice!
As a parting shot, the line below shows how an application (not an applet) might display the three items in the list, separated by spaces:
System.out.println(courseList[1]+", "+courseList[2]+", "+courseList[3]);
The command System.out.println will display whatever is between the brackets on the black console screen.
The + operator links together different Strings so that they appear one after another. If you like, it strings Strings together!
The results of the line would be as follows:
Simon, Bob, Julie
Testing out variables with QuickCup
You can try out the following as a Java Application. This works outside of the browser environment, and as such, can write to the console (black screen) using the system.out.println command.
Note that Java Applications must have
a function called main in the form shown in the listing. Note also that
the source code file must be the same name as the name given after the words public
class in the listing (Vars1) with .java added onto the end - i.e. it
must be called Vars1.java in this case. When it is compiled (using the
button), it will
create a file called Vars1.class containing Java bytecode, which can then
be executed using the java program (click on the coffee cup [
]
icon).
The QuickCup project name in which this source code file appears is called session2_apps.qjp.
| Java Application to look at the functioning of variables |
/*
** Sample Application to demonstrate the use of variables
**
** (c) Copyright 2001-4 Arctan Computer Ventures Ltd
*/
public class Vars1 {
public static void main (String[] args) {
int tot = 0; // define a whole-number (int) variable called tot, and set it to zero
System.out.println("Total is " + tot);
tot = 1; // now set tot to 1
System.out.println("Total is " + tot);
tot +=3; // now add 3 to tot to make 4
System.out.println("Total is "+ tot);
int another_number = 2; // define another whole number variable called another_number
System.out.println("Total is still " + tot); // still 4
System.out.println("Another number is still " + another_number); // still 4
System.out.println("Total * other num " + tot * another_number); // evaluates 4 * 2 = 8
System.out.println("Total is still " + tot); // still 4
System.out.println("Another Number is still " + another_number); // still 2
another_number = tot / 4; // we've lost the old value of another_number - is now 1
System.out.println("Another Number is now " + another_number); // still 2
String course_list[]; // declare a course list attendee array
course_list = new String[3]; // create a new array with three strings
course_list[0]="Simon"; course_list[1]="Bob"; course_list[2]="Julie";
System.out.println("Course attendees: "+course_list[1]+", "+course_list[2]+", "+course_list[0]);
}
}
|
The results, which appear in the black console window, should appear as follows. See if you can match them up to what is happening in the listing:-
| Total is 0 Total is 1 Total is 4 Total is still 4 Another number is still 2 Total * other num 8 Total is still 4 Another Number is still 2 Another Number is now 1 Course attendees: Bob, Julie, Simon |
So now we have an idea of how to store information using variables.
We're going to launch into the concept at the heart of the Java language, object orientation. This rather grand sounding title is, in its essence, quite a simple concept.
What is an object? What is a class?
Well, what is an object in day-to-day
language? It's a "thing". That's pretty much the idea in computer
language terms.
An object is a "thing" that you can identify. The type of "thing" is the object's class. For example, you might have ten bicycles that are essentially the same, but they are all separate objects, perhaps owned by different people. Thus, the class is the general term "bicycle" and the objects are the ten examples of the class "bicycle".
That was simple!
Here's an example of a declared class
public class bicycle { }
And here's an example of a few objects that makes use of the class
uses bicycle;
...
bicycle myFirstBike, mySecondBike;
myFirstBike = new bicycle();
mySecondBike
= new bicycle();
The first line states that we wish to make use of the bicycle class file.
The second line states that we wish to create two objects of type bicycle, the first called myFirstBike, the second called mySecondBike.
The last two lines create new bicycle type objects, and place them in the variables called myFirstBike and mySecondBike.
Every bicycle shares attributes such as colour, speed, direction, make, model, serial number, current gear, whether front/rear brakes are being depressed, etc etc. Only some of these will be relevant to the person using the object. You may have spotted that these attributes are indeed stores of simple information, some of which may vary - e.g. speed. Yes indeed, they are variables. Attributes and Variables are really one and the same - it's just a different way at looking at the same thing.
So how do we change these attributes? Invariably, we'll need to do something to the object. For example, push on the pedal (to change the speed), move handlebars (to change the direction), change the gear etc.
Each of these actions need not translate directly to a change a single attribute. For example, pressing down the brake would not only set the brake pad status to down, but also decrease the speed of the bike.
You may have guessed by now, that these actions are known as methods.
It is a general (but not strict) rule in object-oriented programming that you try not to change attributes directly, but rather use a method to change the attribute. The reason for this is that you may at some future date wish to change the way in which you may update the attribute, or what effect that change makes.
For example, you might change the bike's speed directly now, but if in the future you add a dynamo to the bike, you would have problems determining how to automatically change the brightness of the light according to the speed. However, if you set the speed using a method, then you might add an instruction to the method to update the dynamo light brightness.
Example Bike Class
Here's an example of how we might declare the bike as a class, with attributes for speed, gear, and dynamo brightness, and methods to change these values:-
/*
** Sample Class to demonstrate creating a 'bicycle' class
**
** (c) Copyright 2005 Simon Huggins
*/
public class Bicycle { // Create a new class available outside this file called Bicycle
private int speed=0, gear=5; // Create variables only available within this class
public double dynamoBrightness=0.0;
/* Procedure to push down on the pedal - public, so can be used externally to the bike */
public int pushOnPedal() {
speed++; // Increase the speed by 1
dynamoBrightness=speed/2.0; // Which has the effect of changing the dynamo brightness
return speed; // and return the current speed as feedback
}
/* Procedure to push down on the brake handle - public again */
public int pushBrakeHandle() {
speed--; // Decrease the speed by 1
dynamoBrightness=speed/2.0; // Which decreases the brightness of the dynamo
return speed; // and return the current speed as feedback
}
public void setGear(int new_gear) { gear = new_gear; } /* Procedure to set the gear */
}
|
The class is declared as public to make it available from outside the file. This mean that when another class in another file includes the following statement:-
uses Bicycle;
... then the file will be able to be used, as it is public - available to all.
Bike Attributes
The attributes of the bicycle are as follows:-
private int speed=0, gear=5; // Create variables only available within this class
public double dynamoBrightness=0.0;
You should be able to work out what the first line means - it sets two variable (or attributes) called speed and gear, each of which are both integer type variables. Note also that these are both private which means that they are not accessible outside of the class - so when you create your Bicycle object, you will not be able to read or write directly to these attributes - you will need to use the appropriate method.
The value of dynamoBrightness is set to 0.0 initially, as it the dynamo will be off.
How a method is declared
Note how the method name is formed - in Java programs, we tend to give the method a name that begins with either get or set if it is to change an attribute of the class, and quite often the name of the attribute to follow, but capitalized to distinguish the word set from the word gear - giving us setGear.
If we wanted to pass any information into the Gear parameter, we would put these between the parenthesis. In this case, we don't, so the parenthesis () have nothing between them.
Then the actions to be performed by the method are listed between two curly brackets { and }.
In this case, there is only one action to be performed - gear is set according to what the bicyclist has selected.
Creating some Bike objects
Similarly, if we wanted to use, say, two bicycle objects, we could declare it as follows:-
import Bicycle;
...
Bicycle myBike[];
int bikeSpeed = 0;
...
myBike = new Bicycle[2];
myBike[0] = new Bicycle(); myBike[1] = new Bicycle();
bikeSpeed = myBike[0].pushOnPedal(); myBike[1].setGear(4);
This has the effect of making the Bicycle class available using the import statement, declaring a two-part array of Bicycle objects called myBike and later, defining the array to be two bicycles long, and then creating two new Bicycle objects and placing each into the appropriate place in the myBike array.
Then the first bike [0] gets going by using the pushOnPedal() method - thus its speed becomes 1 and its gear stays at 5.
However, the second bike [1] does not get going, but has its gear changed using the setGear method, setting it to the gear 4 - thus its speed stays at 0, and the gear changes to 4.
Accessing objects
Once you've created your objects, you'll want to do something with them. If we had declared the gear in the Bicycle class as public instead of private, we could have changed it directly as follows:-
myBike[0].gear = 4;
to change the gear to 4. Instead, we must use a method as follows:-
myBike[0].setGear(4);
If we follow through what this does in the Bicycle class, the declaration of the setGear method is as follows:-
public void setGear(int new_gear) { gear = new_gear; }
So the parameter (4 in this case) has to be an integer (4 is, so this is OK), and will be given the name new_gear when used in the commands for the setGear method.
There is only one command - set the attribute gear in the Bicycle object to the value of new_gear (the name of the value passed into the method from outside the object), which in this case is 4.
Note that the semi-colon is needed to show where the end of the command is.
Getting information back from a method
It's all very well making an attribute private, but how can we read it back if we need to?
It is possible to return information from a method - take a look at the pushOnPedal method:-
public int pushOnPedal() {
speed++;
dynamoBrightness=speed/2.0;
return speed;
}
You can see that rather than saying void before the name of the method, we use int to represent the type of information that is to be passed back from the method - an integer. This matches the type of speed which is to be passed back. Note that the keyword void means don't pass anything back, or not applicable.
When the bike's pedal is pushed, the speed is increased (speed++ means increase the value of the speed attribute by 1 - e.g. if it was 0, it will become 1 etc. In some languages, this would be represented as speed = speed + 1; - note this still works in Java, but most people use speed++ as a shorthand.
Note also, that the dynamoBrightness attribute also has its brightness set according to the new speed. It is important that this command comes after the speed change, otherwise the brightness will be set according to the old value of the speed.
Finally, the value returned from the method will be the new value of the speed attribute.
Thus, bikeSpeed = myBike[0].pushOnPedal(); now makes sense - the value returned from calling method pushOnPedal from object myBike[0] will be the new speed (1), whose value will be placed in the bikeSpeed attribute, held outside the bicycle object - e.g. in the rider's memory!
Just a final bit of terminology - methods are sometimes also known as messages - because they are used to send information to and receive information back from objects.
Amending the TextBurst sample to alter its speed
The following listing shows part of the amended Java applet. The parts in bold show the alterations. Type these into the TextBurst project, save the changes, compile the applet, and go on to the HTML section to change the bold parts there. Save the project, and finally run the appletviewer application to test your changes.
public class TextBurst extends JApplet implements ActionListener {
static int maxChangeAmount = 20; // Constant value to define the
// max. speed of colour change
Timer timer; // Used to update the display ever 50ms
JLabel theLabel; // The label that shows the text
int fontSize = 2; // Initial font size (in points)
int fontDirection = -1; //How much the font size will shrink (minus) or grow by
int maxFontSize; // Maximum font size
int redAmount = maxChangeAmount;
int redDirection = - Math.round((float)(Math.random() * maxChangeAmount + 1));
int greenAmount = maxChangeAmount;
int greenDirection = - Math.round((float)(Math.random() * maxChangeAmount + 1));
int blueAmount = maxChangeAmount;
int blueDirection = - Math.round((float)(Math.random() * maxChangeAmount + 1));
Color appletBgColor; //background color for the applet
int timerSpeed = 80; // Timer will start at 80ms
/*
** Initialize the applet - i.e. set up any values before processing begins
*/
public void init() {
String burstText = getParameter("burstText"); // get the text parameter from the HTML page
String timerSpeedString = getParameter("timerSpeed");
if (timerSpeedString != null) // check if the parameter was used
timerSpeed = Integer.parseInt(timerSpeedString); // if so, convert it to an integer
else timerSpeed = 80; // if not, use 80 as a default.
timer = new Timer(timerSpeed, this); // Define a timer so actionPerformed gets called
String fontSizeString = getParameter("maxfont"); // get font size as a string from HTML
if (fontSizeString != null) // check if the parameter was used
maxFontSize = Integer.parseInt(fontSizeString); // if so, convert it to an integer
else maxFontSize = 20; // if not, use 20 as a default.
|
and the HTML portion that should be changed is:-
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
width="500" height="50" align="baseline"
codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0">
<PARAM NAME="code" VALUE="TextBurst.class">
<PARAM NAME="codebase" VALUE="./">
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
<PARAM NAME="burstText" VALUE="Java for Web Page Production - TextBurst v1.0">
<PARAM NAME="maxfont" VALUE="22">
<PARAM NAME="bgcolor" VALUE="#FFFFC6">
<PARAM NAME="timerSpeed" VALUE="160">
<PARAM NAME="scriptable" VALUE="false">
No Java 2 SDK, Standard Edition v 1.3 support for APPLET!!
</OBJECT>
|
Briefly, we have created a new attribute called timerSpeed which we have (unnecessarily!) set to 80ms. Note that it is an integer type attribute (variable), and so can only hold whole numbers.
The getParameter method
The following line:-
String timerSpeedString = getParameter("timerSpeed");
means that we have created a new attribute of type String - i.e. it holds text information - called timerSpeedString, and we are going to set it to the results of a method called getParameter. This method will look in the HTML that calls the applet, and look for a PARAM NAME line where the name = "timerSpeed". If it finds such a line, it will take the information in the accompanying VALUE= section on the HTML page (e.g in this case, it is "160") and place it in a string - in this case, timerSpeedString.
Thus, 160 is retrieved from the HTML page using the parameter timerSpeed and placed in a newly declared string called timerSpeedString. Note that only strings can be retrieved by the getParameter method.
Converting strings to integers using parseInt
The following lines:-
if (timerSpeedString != null)
timerSpeed = Integer.parseInt(timerSpeedString);
else timerSpeed = 80;
look a bit new. Don't worry too much if this looks a bit new. The if command test to see if something is true - in this case, it asks where there was a parameter value found for timerSpeed. If there was, then a method on the class Integer called parseInt is used to convert the the parameter value ("160") held in the timerSpeedString attribute from a string type to an integer type, so that the variable timerSpeed, which is an integer, can hold the value.
Otherwise, if there was no value passed, use 80 as default for the timer speed. Note that this is not strictly necessary, as we already preset timerSpeed earlier.
Finally, the Timer (a bit like a stopwatch) is started, but now it used the value passed from the HTML page, now kept in the timerSpeed variable to say how long to wait between updates to change the font size / colour to give the impression of movement (rather like frames in animation).
timer = new Timer(timerSpeed, this);
If you look on the java.sun.com web site, there is an option called Docs & Training - from here there's a wealth of information about Java.
Click on the link from http://java.sun.com/docs/index.html to browse or download the Java Documentation - this includes the excellent Java Tutorial and the Java SDK reference documentation, which you can use to find information about standard classes etc.
This page also has a search engine facility, which it is possible to download and use locally, or install on your own Java server.
| ??? | Unfortunately, there was not enough time to seek these out at the time of writing - check back on the web site later this week. |