Into Java - Part II

From EDM2
Jump to: navigation, search
Into Java / Part
I II III IV V VI VII VIII IX X XI XII
XIII IV XV XVI XVII XVIII XIX XX XXI XXII XXIII

By Simon Gronlund

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

Introduction

Welcome back to this second OS/2 e-Zine! Java column. I have spent some extremely busy weeks studying computer algorithms, data structures and the complexity of algorithms. Quite a few lab works were done in Java, and it turned out that Java was almost as fast as C, depending on how the code was implemented. But now, together we will explore the always useful questions

Why? How?

Last time we briefly touched the history book, but today we will open the computer theory book. We all know how to make ourselves fried eggs and bacon, don't we? Then we never think about how and why we do certain things. With Java we will try to get the same deep-rooted, basic knowledge. Later we will be able to do the French cuisine. Or whatever happens to be your taste.

Because this got to be a looooooong column, I choose to divide it into three parts: a theory part, a documents part and a lab work part. The theory and lab work chapters will slightly overlap each other, that way it's possible to work through them at different times and you won't need to swap between them too much.

The [java2b.htm theory lesson] of today will concentrate on the basic structure of Java, which in fact is identical to the back bone of object oriented developing. What are the bricks to build with, the small ones and the bigger ones? Taste these words: class, method, instance, data field and constructor. Soon you will be familiar with them.

Further, as developers we'll have to dig into our on-line [java2c.htm Java manual] from time to time. After installing Java 1.1.7 with the Developer Toolkit, as we did last time we met, we now do have a rather big Java on-line manual on our hard disks. The computed size is

[C:\java11]treesize docs
"C:\java11\docs\" and subtree contains:
7.376.136 bytes in 591 files and 3 dirs 7.528.448 bytes allocated

Yes, more than 7 megabyte (size is depending on language of course), cram-full of Java-information for developers. We will find out how to use this huge collection of information, and why it's good to use it.

After so much reading, would you like to do some more coding? Hopefully you don't expect me to give you a 300 line example, or a full blown graphical applet to use. Nevertheless, we'll learn how to do the basic [java2d.htm coding], the how's and why's I initially promised you. Practically every problem that will arise later on, can be solved faster with only a few basic steps.

Theory

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 idea 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.

Java1.gif

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.

Online Manual

The Java environment is chock-full of different classes, methods and possibilities. How to get to know it all? Don't do as I did, my first Java lab work. Last year we were using C in our lab works, so I were used of doing quite a lot of work of my own. If I wished a certain object, I had to implement it myself since not so many classes were predefined.

Now our first lab work was to do a text mode application, holding different objects, like rectangles, squares, polygons, circles and so on. Eagerly I jumped straight into the coding part, the planning and designing phase was quickly rushed through. I think it must have been the transport of joy sipping Java, not decaffeinated. So, I did the tiresome work of implementing things, like an abstract RectangleLike class to inherit from (a very important topic of the next column). Finally it was done.

When I then found out that Rectangle is a Java class already implemented, I didn't laugh too much, I'll say! To my relief I soon found out that I wasn't the only one doing that mistake. But stupidity is only allowed once, isn't it?

Javadoc

If I had bothered using the Javadoc part from the very beginning, a lot of hours could have been saved. Let's save this time right away! Open up a new [java2c.htm browser window] now. Now you can switch between this OS/2 e-Zine! Java column and that new window as you like.

Please navigate to your Java11 folder. There, find the docs folder, then the api folder. Perhaps you have installed Java 1.1.7 on the C disk, so the path will be C:\Java11\docs\api. Now open the packages.html. For most purposes this is a good starting point, so bookmark it in your browser.

I am not one hundred percent pleased with this IBM documentation. Everything is there, up to 1.1.7, but try for example to load the "index" page. It is a file called AllNames.html, and it's 1,430 kilobyte big. Yes, you were correct, 1.43 MB, and in spite of being on your HD it is still slow to load every now and then. IBM, please make this index file in smaller chunks.

Soon you'll see for yourself why I grunt about this part, but I will explain my feelings right away. Often you have a feeling of what method name to expect, but you would like to check it out. Let's imagine, we are looking for a method that will draw a filled rectangle on the screen. Possibly the method name will be drawRectangle, but we aren't sure, and we don't find this method in the class Rectangle. We will try using the Index. There we click the "D", scrolls and there we are.

After many seconds we have found that the drawing method resides in java.awt.Graphics, that is the class Graphics. But it wasn't drawRectangle we were looking for, since it only draws the outline. A shortcut now is to click the "drawRectangle" and hope that the expected method will reside nearby. Yes! Within the Graphic class, the method above is the one, "fillRect". Consider doing this kind of search a dozen times an hour, with tens of seconds running away waiting for the browser to work every link we use, soon you will get rather tired.

SUN

Better then is the Java docs found at Sun web site then. At http://java.sun.com/docs/ you will find the documentation, on-line docs and zipped docs for download, for both 1.1 and 1.2. The pro's with 1.2 is that it's available with frames, but using 1.2 you have to watch out, stuff not implemented in 1.1, clearly marked 1.2, is there. Chose whichever API you like and download it, unzip it to a new folder of your wish, and please, replace the bookmark with this one. The printing is the same, but it's chunked to handy parts and therewhy much faster. The framed 1.2 docs are really a dream.

How to use it?

There is no standard way to use an API (Application Programming Interface) documentation. You'll have to navigate around to acquaint yourself with it. Soon you'll know the most common classes, but to save yourself pain and thoughts, if you find a class frequently used, then study the documentation of that class deeply. You might find interesting ways and methods to do a lot of tasks. Follow the links around to see how they interact. That is a good way to learn Java quickly.

Mainly the documentation is divided in three categories; the packages, the classes and the methods within a selected class. The Java11/docs/api/API_users_guide.html will give you the basic introduction. I suggest you turn to that page soon and study it.

To sum it up, most time we are going to develop Java app's, we will have a browser open at the same time. I often find myself switching between the code editor and the browser quite a lot. Many times I know what I would like to do, and I know how to do it. I still search the API to see if there is a better way to do it, another method or perhaps to get some other angles of approach.

Of course there are a lot more to know than is written in the API, which for a beginner is too poor. Therefore, never miss an issue of OS/2 e-Zine!

Lab Work

Welcome to the hands-on part of this Java column. Up to now we know of classes, methods, constructors and data fields, and that really seems to be a lot, isn't it? In spite of that, we cannot rush of and use the more subtle parts of Java this time, we will control ourselves and stick to text mode. Nevertheless, we will make ourselves one class and a simple test application to bring our class alive.

A few more details will be discussed, like header, body, toString, new and a few syntax details. Yes, I am well aware of this being a veeeeery long column. Isn't it always so, at first there are quite a few things to get the hang of, and later it doesn't feel much. A few years back I started out learning the Persian language, a spoken language, not a programming language. In the beginning the curve was steep, believe me. Not a single character was alike our western alphabet, but as soon as I got hold of it, everything seemed much easier. So this Java column will, too.

Again I'd like to repeat that a basic programming knowledge is assumed. Most of the code is understood by the context, but a good source of general programming knowledge is the REXX column by Dr. Dirk Terell, began in OS/2 e-Zine! v3n4. The general coding style is coherent within this family of programming languages.

The Bank Account

In any object oriented language, the Bank Account (BA) is one of the most commonly used illustrations to discuss the basics of classes and objects, and we will use it as well. A BA is an object, in this case a record of our means. Creating a BA as a class is wise. Whenever the senior accountant finds out that we have to change a few things in the BA's, it's an easy task. Do it once in the classes affected, and we're almost done. In languages not object oriented, we have to search most of the code to find out if we need to adjust anything.

The first thing we always will do is to make a rough outline of what we expect of a new class. This technique is always useful, my first computing lecturer pointed out that "application code is 90 percent penciled and the remainder is typed by the keyboard". I start to believe it's true, most of the 90 percent anyway. If we skip this part we soon will have to pay with blood, sweat and tears.

Any BA uses a name for the account holder, a balance, a way to deposit and redraw money. For a lite BA that's all, the first pencil part is done. Let's make ourselves a new folder within our OS/2-eZine_Java folder, named Bank. Now we will continue with writing ourselves a class named BankAccount using our favorite editor, and we will save it into this new folder using the name BankAccount.java.

import java.io.*;                // 1
public class BankAccount {       // 2
     protected String name;      // 3
     protected int balance = 0;  // 4
}                                // 5

Line 1: A statement that informs the Java compiler to import from the io class of the common Java environment whenever needed to. In fact this line is redundant. Our applications will always have full access to the io class, and a few more classes - the fundamental Java classes - but we use this line more as an illustration.

Line 2: The class header, providing the class name, BankAccount. The public part tells the system that anyone, practically, could use this class to create their own instances from. In spite of that, anyone will not have access to our objects, as we soon will see.

At the end of line two there is the { , the beginning of the body of the class. Along with the finishing } it encompasses the entire class body. This far the body is nothing more than two data fields, the name and the balance.

Line 3: We assume name will be spelled with alphabet characters, as we usually write names. Therefore, we declare name to be of the String class. At this time we don't know anything about the holder, even more less his name, hence we do no initialization.

Line 4: Preferable we will only handle real dollars and never cents, that's why we declare balance to be an integer, an int. Unless this bank will credit us with an initial amount as a welcome gift, we must initiate the balance to zero at the creation.

This initialization to zero is not necessary to do here, but it's convenient. Even though the bank will use welcome gifts in the future, or only for certain BA's, it doesn't hurt to initiate to zero. On the contrary, think of what could happen if we didn't initiate to zero, and we'll forget to give balance a value upon creating an instance of this class. What will happen if we later will try to redraw money from it? There is no money, so we couldn't rob the bank, but the redraw method will get in trouble, since it will find null, which is more nonexistent than zero.

Protected

What about that protected at the beginning of line three and four? We said that the class is made public, so anyone could use it to make their own BA's from. But we will certainly not let anyone else touch the stuff we have within our BA object. Therefore, we hide the information within the class, we protect it so that no-one could not "see" or manipulate the data fields. Now only methods within the class could change or access the data. There are other access modifiers as well, that we'll discuss when we encounter them.

Methods

Now we have to make ourselves several methods, a few already mentioned, which we could start with. Any method is put within the body of the class. In the same manner as a class, methods too have headers, and bodies encompassed by { and }. Let's start.

The very first method, a method we will always use, is the toString(). It is an easy method to write and it's self-explanatory. Why use this method? If any thing goes wrong Java tries to give us a clue of what happened. At that time it will present us the brief, or long if we like to, information we have stuffed in toString(). This is why it's a good practice to use toString(), it will surely save you expensive hours debugging your code.

toString() will not print by itself through the System.out, but it's invoked by the Java run-time environment. Or by ourselves if we like to. Usually it returns a String, telling us a few details, and so give us an identifying description.

public String toString () {              // 6
return "Class BankAccount: " + name;     // 7
}                                        // 8
public void deposit (int value) {        // 9 
if (value >= 0)                          // 10
balance = balance + value;               // 11
else {                                   // 12
System.out.print("You cannot deposit " + // 13
"a negative sum of money: ");            // 14
System.out.println(value);               // 15
}                                        // 16
}                                        // 17

Line 6 and 9: As the class is, methods are made public. A future column will discuss protected methods. String tells the compiler that toString() will return a text string, and void that this method will return nothing. Why so? you may ask. That way the compiler makes sure we know what we are doing. We will not be allowed to request a String from a method that will not return nothing.

What about the (int value) part? As discussed in the theory chapter, this is the information receiver. We have to tell the compiler what kind of information to expect, if any. We will leave it with that for now, but there are really useful concepts out of that. Here we say that the sum to be received, and assigned to value, must be an int.

Please note, whenever we mention a method, usually we will write x() , and the parenthes denotes we are discussing a method. This is because we are allowed using exactly the same name for data fields as well, e.g. price and price() are a data field and a method respectively.

Line 10 and 12: Here we do a simple if - else test, and I think the purpose is obvious. It's always good to know that the cashier cannot mistakenly do a typo of minus one million dollars, and drive you bankrupt the very week you sold your Intel shares. She will be directed to line 12 if she did wrong.

An else is not necessary, we use it only whenever we actually need anything to be done as an alternative. Another time we will learn more about how to use if, else, else if and a few more.

Please note the { } encompassing the body of the else. These are necessary as soon as more than one statement are to be executed. Therefore, we do not need them for if, which only have one statement.

Line 11: Add the sum of money to the balance. Within the object the data fields are visible. They are only invisible to objects and methods outside the object they belong to, because we made them protected.

Line 13: A line with this text will be printed if the cashier made that typo, and nothing will happen to your balance. Try to deposit again.

Line 15: The wrong value will be printed. Compared to the HelloWorld, we see that it would have been possible to use the + sign at line 14, to add further information to be printed. The only reason of this new line is to show a tiny difference between print() and println(). In the HelloWorld app we used print(), but then we had to finish the line with the "\n" operator, 'end-of-line'. The subtle difference between these two methods is that println() does a line feed by itself.

What is a BA if we cannot withdraw money from it? Let's continue:

public void withdraw (int value) {                // 18
    if (value <= balance && value >= 0)           // 19
        balance = balance - value;                // 20
    else {                                        // 21
        System.out.print("You cannot withdraw " + // 22
        "that sum of money: ");                   // 23
        System.out.println(value);                // 24
    }                                             // 25
}                                                 // 26

Line 18: Despite we withdraw money, it isn't the withdraw() method that hands them to us. Hopefully we'll get them from the cashier. That's why it have void as return type, but withdraw() will justify the balance.

Line 19: There is no big difference from the deposit(): if - else line, except two things, a small matter of taste, and a great opportunity to discuss how comparisons will evaluate. The most obvious comparison is whether we try to withdraw more money than we are credited. If so, we are directed to the else alternative printout. Maybe you ask, "Why not tell the balance at the same time?" The simple answer is, don't let a method do more than it's supposed to do. It's better to create another method doing that part of the work, a querying method that we could use for other purposes as well. Admittedly, it's a matter of taste.

In the middle of the comparison line there is a double &&. This notation is used for AND. It will guarantee us that both comparisons are true, we still have credit left AND the amount we want to withdraw is correctly typed, a negative value would actually be a deposit. Cool, but unfortunately the bank will soon find out.

Why did we write the "do we have enough money" check before the "typo" check? Despite all those bugs we see too often, developers actually have been thinking. One thing with an AND comparison is really trivial: both left side and right side have to be true. If the if finds the left part false, it is redundant to check the right side, so it does not. Smart, he? Then it's up to us to figure out which comparison is most frequently false, and put that one first, and that way saving a few CPU cycles.

Exactly the same reasoning is true about OR comparisons, it's enough finding one true left OR true right. Put the most frequently true to the left. Every composite comparison will evaluate from left to right, and stop whenever a conclusion is made.

public String name () {  // 27
    return name;         // 28
}                        // 29
public int balance () {  // 30
    return balance;      // 31
}                        // 32

These two useful methods will give us an opportunity, the only one indeed, to have a look at the two data fields. Since the fields are protected it isn't possible for anything, except public querying methods within the object, to return those data.

Line 27 and 30: The double parentheses () are empty, nothing is needed to be able to return the data stored in the data fields. To show the difference, we will make a method used whenever we would like to change a name. Maybe the customer got married, or whatever.

public void name (String newName) { // 33
    name = newName;                 // 34
}                                   // 35

How come both methods could use the same name name()? Because the compiler is viewing them as two different methods, actually name(void) (although void is not written, but understood) and name(String). As Jones, James is not Jones, John. Powerful, isn't it?

Now we have a complete class, with two data fields and six methods. Everything is written within the encompassing { } parentheses of the class.

Constructor

Could we now make an instance out of it? Actually not! The constructor will come to play an important role. At first, we could always make the basic constructor, which takes no parameters at all. That's the easiest one, but not always to recommend. Think of a database record, why create a new record but without data stored in it. Mostly we press Cancel those times, don't we? Other times it suits our intention very well to make zombie objects, and later bring them alive.

public BankAccount () {  // 36
    super();             // 37
}                        // 38

Constructors looks a lot as methods, and they are in many respects. But we cannot invoke them, as we invoke methods. And they never returns anything. Constructors will only listen to a special operator, the new operator discussed below. And they are named by the class name as we see.

What is super()? Without going too far, we can say that it's a call to the System parent, to let the environment constructor create a new general object. super() is sometimes not written explicitly, but it is always there, it's implied. If we from now on leave it out, it's understood.

Anything else isn't done within this constructor. The object is now created, we have our BankAccount instance at hand. However, if we didn't initiate balance to zero at line 4, we can do it here, in the constructor. If so, we have to add a line balance = 0; within the body of the constructor.

public BankAccount (String n) {             // 39
    name = n;                               // 40
}                                           // 41
public BankAccount (int amount) {           // 42
    balance = amount;                       // 43
}                                           // 44
public BankAccount (String n, int amount) { // 45
    name = n;                               // 46
    balance = amount;                       // 47
}

With these three more constructors we can create a BA any way we like, but maybe that one with a balance but no owner is more for Swiss banks to use. The [java2e.htm BankAccount class] became 47 lines long, but it surely is a lite BA. It's clear anyway that classes don't need to be several hundreds of lines. A few weeks ago I made one only 10 lines long, but on the other side, I needed about 2,500 instances of it for my lab work.

To make this class work, we have to use the code found in [java2f.htm MyBank.java]. Objects like BA are rarely running by themselves. MyBank is a short test application. It will create a few BA objects, assign them owners and do a few transactions.

new

OS/2 - Window
[X:\]javac MyBank.java
[X:\]java MyBank
...
...
...
[X:\]
Compile and run your Home Java bank.

The only new thing in MyBank is the new operator. Above I stated that the constructors only listened to a special operator, that's new. This operator will order the creation of a new instance of the actual class. It's as simple as that. Next time we will discuss it a little bit more.

After you have edited MyBank.java, copy it into the Bank folder. As we did the last month, we compile this Java file into Java byte code, and then run it.

Why don't we compile the class BankAccount.java? Simply because javac is smart enough to understand that it needs to compile that class too, since it is used by the MyBank class. That's convenient whenever making minor editing on any class in a bigger app, only run javac on the main class, and the compiler finds out by itself that only a few *.java files are actually edited, and compiles them.

Please, experiment with MyBank as much as you like, nothing will be crashed or screwed up, the nasty and foul-mouthed compiler will amuse you. Ctrl + C will stop every process out of control.

Summary

We have labored hard this time, examining the difference between class and object, the blueprint vs. the real object, created by the new operator invoking the constructor. Both classes and methods are made by headers and bodies, the headers providing vital information to us and the compiler.

The data fields have to be declared and maybe initialized. Initiation could be made at the declaration, or in the constructor. Neither is absolutely necessary, we might give data field's values later on.

The importance of the penciling phase and of toString() was emphasized, since it will save us a lot of late nights and brain work in the future. With this knowledge we now are prepared to advance into the Java world of living creatures, objects and ways to master them all. Have a nice adventure. See you next month!