[Previous]
Into Java, Part II - Theory - by Simon Gronlund
[Next]
OS/2 e-Zine!

Go to a Printer Friendly version of this page



Lash Back! - Join in the ongoing public discussion with our interactive forum. Be frank, be vicious, you can even be anonymous.

- or -

Blast Back! Send a private message directly to Simon Gronlund with your thoughts:

Contact OS/2 e-Zine!

Sponsored links:

Summary: Simon continues his exploration of the Java language... with sample code.

Into Java, Part II - Theory

By: Simon Gronlund

The theory lesson of today will concentrate on the inner parts of your Java apps, the basic structure of Java. How to develop with Java? Normally people think of computer programs as a set of instructions executed one after another, interspersed by quite a few tests, as:

if (Simon == happy) then smile(); else comfort();

However, except some odd beings in Hollywood, no-one usually thinks of an artificial world within the circuits of their computers. A world of living objects, with intelligence, power and lives. Nevertheless, Java is really inhabited by that kind of beings, creatures living within the binary world. At least, it can be good to visualize Java objects that way.

Even though the Object Oriented thinking was thought of as far back as in the 1960's, it never surfaced until the Xerox Palo Alto Research Center (PARC) era ten years later. At Xerox PARC Alan Kay and his group developed Smalltalk, an easily understood object oriented language. Soon object oriented developing was the key word of the day, within no time C++ was born, and the rest is now history.

Besides an easy and forgiving syntax, the basic idéa with Smalltalk was the object properties. Thinking of objects like Printer, Queue, Document or User, made it possible for ten year old children to write their own applications at Xerox. How come?

Objects

Think of an object, your mouse for example. What about it? Most mice have two or three buttons, a cable, and you are supposed to move them around. So, the mouse device have some properties we are well acquainted with, move the mouse and the pointer on the screen moves. A left click will stir up an action, a left double click maybe fires an application, and a right click causes another action. If you do press the left button at the same time you're moving the mouse, normally you'll mark an area on the screen.

For most people it would be easy to tell these properties, specify them on a paper and even tell a technician what they expect out of the item, right? That's because every object has certain behavior, and a certain look ~feel. Thinking object oriented is that easy. Specify the behavior you want of an item, and maybe the look if the item is visible, and you're done.

Then, how to code a mouse? We won't do a working mouse, but it can serve as a good image of how the object oriented (OO) developing works. First, we need the outer skeleton, the outer Case, so to speak. We need two Buttons, as well as some kind of a RecognizeMovement device underneath, and we shall not forget the Cable.

Cases, Buttons, RecognizeMovement devices and Cables are rarely things built for this Mouse purpose only. No, on the contrary, we can go buy these things at any well-stocked hardware store. Maybe not exactly what we were looking for, but suitable enough. With a little polishing them up they will do. How come? It works because they have a basic design, they are made by kind of a pattern. Patterns that even children can think of and use, from the day they are given their first LEGO package.

Class

A pattern, better known as a class, provides a description of the object we will buy or build. Any kind of object that will react in a certain way when we click upon it, may be categorized into the Button class. Put in another way, a class is a category of certain objects. So, a Switch is another class, since it doesn't have a similar look, and it doesn't work in the same way.

Spelled with initial capitals, classes are easily identified in the code.

That will help us find three different classes in the HelloWorld app, shown below: The class we wrote ourselves, HelloWorld, the System class and the String class. The latter are classes someone else developed for us, ready to use.

The class body is encompassed with { } parentheses. We may place those brackets on new lines, or where ever we like to, as long as they encompass the method body.

Methods and constructors, discussed below, are spelled with initial small characters.

Only if a method is composed by several describing words, like getMilkToAfternoonCoffee, every following word uses initial capitals, to make them more readable I suppose.

As with classes, the code we write ourselves within the method bodies, are always surrounded by the curly { } brackets.

Data fields are spelled as the methods are, with initial small characters and composed the same way.

Data fields needs to be declared and their type must be specified. it's not necessary to initiate them at declaration time.


The way I place the parentheses and brackets is a very common standard, easy to read and providing a little space between different parts of the code.

What is then telling Classes apart from each other? That's a tricky question. The one to judge is you, but there are a few hints. A class will have its own properties. A class could look like another class to a certain degree, but if they are too similar, maybe it's better to merge them into one class. Think of a push-button, that's a Switch, isn't it? Although it looks like a Button, it has properties of its own. But maybe, in a soon future, the engineers at your shop changes the construction to a "soft" push-button, maybe an electronic one. Is it still a push-button in the Switch class? Maybe, maybe not.

On the contrary, take a look at the cable. Once upon a time a cable was two plastic or rubber covered copper wires. By the time more wires were added, more dimensions were manufactured and the covers were colored differently. Still a cable, isn't it? Except that some wise guy invented the coax, a single wire with a metal shield covering the isolation, and a thin cover over it all. Still a cable? Or not? I would say "Not!" because so many new properties were introduced with this new cable. It is a cable, but it deserved a class of its own, that can better describe it's behavior.

The interior of the class, that is called body, holds the entire information about how the class looks like and what it can perform. That is, data fields, constructors, and methods. The body of HelloWorld, shown below, starts at the end of line 8 with a curly bracket, and finishes at line 18.

Instances

Until now we have been discussing classes as if they are patterns for certain objects. Objects that can be categorized into groups, narrow or wide groups. Yes, classes are not the objects themselves. Classes are the abstract descriptions of the objects we whish to create. If we whish to create a button, we'll go to the class Button, and then we will create a button object out of the blueprint found in the class. We are creating an instance of the Button class. From the Button class we can make ourselves as many instances, or objects, we like to.

Every instance of a certain class does have exactly the same property as the other instances have. At least at the moment before creation, because we are allowed to give it a few states upon creation. A button for instance, perhaps data sent to it at creation time will be added to the label upon it. And of course, as soon as we click it once, it changes a few of its internal states, maybe it'll be turned "on."

It's these instances we consider objects, not the classes. Classes are merely the description, the blueprint. An instance is the realized class, the object that inhabit the digital world of your computer. Since any instance lives a life of its own, with its own properties, its own intelligence, its own abilities, we can certainly consider them living objects.

That's why children easily grasp the OO idea quickly. As they put their different LEGO parts together to form another object, they can put OO objects together. The OO concept isn't trickier than this, using different classes to get a composite whole.

Constructors

How to create instances from classes? To make this creation possible we need a method to construct them, a constructor. This part of the class code holds part of the class description. Especially it holds the code of what to do upon creation, maybe create other instances, or how to tie objects together. The importance of the constructor will reward it a chapter of its own in a future column.

However, if we briefly look to our HelloWorld app we won't find a constructor in it. That is because this particular class secretly calls another constructor, a constructor hidden in the Object class. The Object class is a class of the general Java environment, that is always there, but mainly hidden to us. Remember, a constructor is always needed, one that we'll make ourselves, or a default constructor by the system.

The Mouse we're building will have a constructor would create instances like the Case, Buttons, Cable and the RecognizeMovement, and tie them together to form the mouse object MyMouse. It will certainly initiate most of these instances to neutral states.

Method

Every object has some actions to perform. Sooner or later we will ask it to do something. The Printer instance will get a print work to do, the buttonPressed will cause a signal sent to the computer when it's pressed down, and later when it's released. Most instances will perform a task in due time.

The part of the code written to stir up some action is called method. Other programming languages call it function, procedure, etc. A Mouse class has some methods, as pressed(), released(), moved() and so forth.

The HelloWorld method body starts at the end of line 14, and closes at line 17, encompassed with curly brackets. On line 14 the main method is called by the Java Virtual Machine (JVM), to start the application. Line 15 and 16 are calling another method, print, that will tell the System object to print our message, and finish it with a "new line" command, line 16.

If we need to pass information to the method, we enclose this information within common ( ) parentheses. Line 16 is a good example. We are invoking the method print of the out object, that's in the System object. We see ("\n"). The "\n" is the information we sent along with the call to the print method, encompassed with ( ).

Now look carefully at line 14 and the main method. Within a couple of ( ) we find String [ ] args. This is the way to let any method receive information, it is "poured" into the two parentheses. The type of information expected is explicitly stated, this time to be String. The main method can be invoked with parameters, or arguments. As any method, main receives that information within two parentheses.

This is exactly what happens if we, for instance, writes

dir \s \p


The \s \p are the parameters, which are passed to the dir command, that we this time can consider a method. In Java the parameters to main are received as one text string, of the type String, and will eventually be parsed.

Data field

At the end of this part of the column we'll discuss the data fields. A data field is exactly what it says, it's a field in the computers' memory holding our data. Java is very sensitive about which kind of data we are storing, and we can compare the reason to if you are asked to take care of a persons possessions. There is quite a differense in storing space between a book and a book shelf, between a bike and a car. We know that, but how to let the compiler know of it?

To tell the compiler how much space to request we have to tell the type of it. Then the compiler will look at that class to find out how much memory the application will have to ask for each time necessary. The most general type is Object, which doesn't say nothing about what kind of stuff we like to store in that data field. Mostly we will avoid that, but sometimes it can be useful to know how to fool our compiler.

Java being that hysteric about the type of data fields (called strong typing), is something we shall use and be happy about. This property gives Java, and most OO languages a certain strength and powerful abilities REXX cannot give us. On the other hand, we need to learn about the types.

Declaring variables and initiating them

Everywhere we need a data field, we must declare the data field explicitly. In reality this is to tell the compiler how it will handle this variable, which is another common name for the data fields. Two examples of data fields are seen in the HelloWorld app at line 11 and 12, the data fields "hello" and "world", of the String type. In this app we do declare the String variables and initiate them at the same time, line 11 and 12. Initiating, or giving the variables a value like "world", is not necessary to do at once. We did it now, but other times they are only declared, and given values later on.

In our thought Mouse class, we have to declare the objects like this

protected Case case;
protected Button leftButton;
protected Button rightButton:
protected Cable cable;
protected RecognizeMovement reconMove;
protected boolean pressed;
protected int speed = 0;
protected int x;
protected int y;


We can see the five different mouse parts, from which classes they are derived, and which name we are giving their instances. One variable can hold a true/false value. Further there are the variables' speed, x and y, which can hold integer values. Only the variable speed is initiated to zero, the others aren't initiated at all.

Summary

We have now encountered every basic part needed to build ourselves Java applications. We have met class, the blueprint of the object we like to create. We found out that a realized object is called instance. To create an instance we are in need of a constructor, the code that will initiate the variables of the object, create other objects and tie everything together. We discussed the method, the action-performer, that will do certain specified tasks that we code it to do. Furthermore, we looked into data fields, or variables, and how to declare them, and eventually initiate them.

Introduction
Java On-Line Manual
Java Lab work
[Previous]
 [Index]
 [Feedback]
 [Next]
Copyright © 1999 - Falcon Networking ISSN 1203-5696
November 1, 1999