Вы находитесь на странице: 1из 11

8966468.

doc FBE – Computer Science Dept

Mekelle University Faculty of Business & Economics

Computer Science Department

Comp 262: Internet Programming with Java

Handout 2 – Java Basics Using a Simple Class

1 A first Java Program – using BlueJ


This handout covers your first Java program, using BlueJ as an editor.
The program is used to introduce some Java concepts such as instantiation of objects,
garbage collection and the use of the main() method. It also gives an introduction to
using BlueJ.

1.1 Start BlueJ


To begin with, we will use the BlueJ development environment.
• Start BlueJ (there should be a short-cut icon on your desktop – it looks like

this: Bluej.lnk )
• If the windows that displays has the title 'BlueJ Launcher', then you need to
tell BlueJ what Java VM to use. If it does not have an entry in the list (i.e. in
the columns Path and Version) then you need to browse to find the VM.
• Click the Advanced button and then click Browse for a Specific Java version.
• Browse to the folder C:/j2sdk1.4.1_03 (the version number installed on your
PC may be an earlier one e.g. 1.4.0 – this is ok). If you cannot see this folder,
it may be hidden. To show hidden folders, open My Computer, go to the Tools
menu, choose Folder Options and then go to the View tab. Under 'Advanced
Settings', find the option that says 'Show hidden files and folders' and turn it
on. Click OK. Now try to find the j2sdk folder again.
• When you have browsed to and selected the C:/j2sdk1.4.1_03 folder (or
nearest version you have), click Open.
• The BlueJ Launcher should now show an entry in the list of available Java
versions. Select the entry and then click the Launch BlueJ button.
• When BlueJ starts, it starts up two windows – one is the BlueJ main project
window and the other is a command prompt window. You work in the main
project window, and do not do anything to the command prompt window – as
this is the Java compiler which BlueJ needs to have running.

1.2 Create and Compile a Class


In BlueJ, you work with a project – you can create a new project or open an existing
one through the Project menu.
• Go to the Project menu, then choose New Project…
• Navigate to where you want to create your project and enter the name
FirstJava for it – BlueJ will create a folder with the name you specify; you

Page 1 of 11
8966468.doc FBE – Computer Science Dept

should try to create all your Java projects in a Java folder somewhere on your
H: drive.
• Click the Create button.
• You should now see a screen like that in Figure 1 below. Any files in the
project folder are represented graphically – BlueJ has automatically created a
text file named README.txt in the project folder, this is the icon you can see.
Double click on the icon to edit the ReadMe file. It is good practice to put
some information about the project into the ReadMe file, for other users to
read.

Figure 1 – BlueJ screen after creating a new project named ‘FirstJava’

We will start by creating a class – all the code in a Java program must be included in a
class (because Java is a true object-oriented language); you can have as many classes
as required in the program.
• Click the New Class… button.
• You have the option to create one of four types of class – Class, Abstract
Class, Interface or Applet. Choose Class and enter the name FirstJava for the
new class.
• Click OK.
• Your BlueJ project screen should now look like Figure 2.

Page 2 of 11
8966468.doc FBE – Computer Science Dept

Figure 2 – BlueJ screen after creating a new class in the FirstJava project

• The yellow filled rectangle shape represents a class (like a class diagram). The
stripes on the rectangle indicate that the class has not yet been compiled.
• To see the code in the class, select the class and choose Open Editor.

BlueJ has created the basic structure of the code for a Java class for you.
This gives us some of the basics of the Java language, as follows:
• A block of comments starts with /** and ends with */. Each line in the block
has a * at the beginning of it.
• A single line comment just needs a // at the beginning of it.
• The @author and @version tags in the comment block are used by the
JavaDoc program to automatically create documentation about a class. They
do not have to be used or set, but it will help to create useful documentation if
you are working on a large project. Other tags used in this class are @param
and @return – in the comment for the method sampleMethod(). The
programmer must put in the values that they wish to appear in the
documentation generated by JavaDoc e.g. put your name after the @author tag
– on the same line, leaving a space between the tag and the name text.
• A class is declared with the keyword class, followed by the class name. The
keyword public specifies that this class is accessible to all other classes
(similar to the public modifier in C++).
public class FirstJava

Page 3 of 11
8966468.doc FBE – Computer Science Dept

• The class definition begins with a { and ends with a } – curly brackets/braces.
Curly brackets are used to mark blocks of statements in Java.
• All statements are ended with a semi-colon (;)
• The data belonging to the class is then defined, by variable declarations.
Variables used in the class are usually declared at the top of the class. A
variable declaration consists of an access specifier, a data type and a name.
private int x;
This line declares a variable named x, of type integer. The access specifier is
private – this means that this variable is accessible only to this class, and not
to other classes. This is the opposite of the public access specifier.
• Next is the class constructor. The constructor is like a special method that
contains code that will execute every time an object of this class is
instantiated.
In this example, the constructor simply initalises the x variable – initialising
means assigning an initial value to the variable. The constructor is used to set
up values that identify the object e.g. for a Customer class, the constructor
might set the Name of the customer. It can also make calls to other methods in
the class.

/**
* Constructor for objects of class FirstJava
*/
public FirstJava()
{
// initialise instance variables
x = 0;
}

It does not matter where in the code the constructor is placed – but it does
have to have the same name as the class, and this is case-sensitive.

• After this, the methods of the class are written (remember that methods are
what allow other classes to communicate with this class – the messaging
concept of OO). This example shows a simple method that takes one
parameter – a parameter is defined with a data type and a name, in this case it
is named y and is an integer.

/**
* An example of a method - replace this comment
with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public int sampleMethod(int y)
{
// put your code here
return x + y;
}
In Java, a method must have a data type to indicate the type of value it will
return. This method will return an integer value. It is also possible for a

Page 4 of 11
8966468.doc FBE – Computer Science Dept

method to not return anything – to specify this, the keyword void is used as
the type.
Again, the public keyword is used – this specifies that this method can be
accessed by other classes. If the method should not be accessed by other
classes, this can be changed to private.
• The return keyword is used to return a value from the method – in this case, it
simply adds the values of the class variable x and the parameter y and returns
the resulting value.

Now we need to compile this class:


• Click the Compile button (at the top left of the class code window)
• When it has compiled, the message ‘Class compiled – no syntax errors’ should
appear in the small text window at the bottom of the code. If there were
compile errors, they will appear here.
• If it has compiled successfully, close the code by clicking the Close button at
the top of the window.
• You are then returned to the project window – and because the class has been
compiled, the yellow rectangle is no longer striped.

1.3 Create an instance of the class


Now that the class has been compiled, it is possible to create objects belonging to
the class. Normally, you would write more Java code to create an object of the
class – e.g. another class that creates an object from this class. But BlueJ gives us
a very easy way to do this, so that we can quickly see what an object looks like
• Select the FirstJava class and right-click
• Choose the first option – ‘new FirstJava()’ – this tells BlueJ to create a new
instance of the FirstJava class.
• The Create Object window appears – this contains a text-box for naming
the new instance. Once you have a class definition, your program can
create many objects of that class. So, to identify different objects, each has
a name – a bit like a variable name, which can then be referenced in code.
• Accept the default name (something like ‘first_jav1’) and click OK.
• A red shape representing the object now appears at the bottom of the
screen.
• Right-click on the object – this gives you these options:
o Inherited from Object
 Every class in Java inherits various standard properties
from the built-in Object class. This option allows you see
what data and methods the object has inherited from Object
and any other super-classes the object has.
o int sampleMethod(y)
 any methods in the class are shown here – click on a
method to invoke it. If the method requires parameters, the
dialog allows you to enter them. For this one, you can enter
a value for y then click OK – the return value of the method
is then displayed.
o Inspect

Page 5 of 11
8966468.doc FBE – Computer Science Dept

This allows you to check the state of instance variables for



this object. For this object, the state should show ‘private
int x = 0’ – because the x variable was initialised to 0 when
the object was constructed and no action has occurred to
change it.
o Remove
 Use this to delete the object when you are finished with it.

The Lab Exercises 1 session includes some exercises in which you will modify the
FirstJava class and create a new class to interact with it. So you should ensure you
save this class so you can use it again.

Figure 3 – BlueJ screen showing the compiled FirstJava class and one object that is an instance of
that class

1.4 Running a class from command line


BlueJ’s GUI allows you to easily run a class, by creating an object from the class.
Outside of BlueJ, another way of running a class is needed. This is done with the
main method. In a stand-alone Java application, it is necessary to have one class with
a main method – the main method is how the program is kicked off (applets are
different – they do not require a main method to be executed). This is because when a
Java interpreter is run, it needs to be given a class name; it then looks for the main
method in that class.

Page 6 of 11
8966468.doc FBE – Computer Science Dept

An example of a main method is as follows:

public static void main (String args[])


{
//instantiate an object of the FirstJava class
FirstJava firstJavaObject = new FirstJava();
System.out.println ("initial value of x is:" +
firstJavaObject.x);
//increase x by 5
firstJavaObject.x = firstJavaObject.x + 5;
System.out.println ("value of x after adding 5 is: " +
firstJavaObject.x);

}
A main method must always be declared as 'public static void' and it must also have
one argument which is an array of data type string (String args[]).
Any arguments that need to be passed in can be passed as values in the args array.

The keywords public, static and void can be used with any methods. Public and static
can also be used with variables.
public – specifies that the method is accessible to all other classes and to the
interpreter
static – this keyword specifies that the method is one that is associated with the entire
class, it is not associated with objects belonging to the class. The main method must
always be static because the interpreter uses this method before any objects are
created – it is the gateway into the program. Section 1.7 gives some more information
about static methods.
Void – specifies that the method does not return any value.

The code inside the method carries out these steps:


1. Create (instantiate) a new object from the FirstJava class and name it
firstJavaObject
FirstJava firstJavaObject = new FirstJava();

2. Print out the value of x for firstJavaObject, to the default standard output
System.out.println ("initial value of x is:" +
firstJavaObject.x);

System.out.println is very useful for debugging a Java program – e.g. to check


the values of variables at different points in the code. BlueJ sends this output
to a terminal window.

3. Increment the value of x by 5:


firstJavaObject.x = firstJavaObject.x + 5;

4. Print out the new value of x, after the increase:


System.out.println ("value of x after adding 5 is: " +
firstJavaObject.x);

Now, paste or type the above main method into your FirstJava class, then compile the
class. In BlueJ, right-click on the class rectangle – there is now an extra option in the

Page 7 of 11
8966468.doc FBE – Computer Science Dept

menu, 'void main (args)'. Select this option. A dialog allowing entry of arguments then
opens; click OK. The main method is then run, and the results output to a terminal
window.

You can also use the main method to run the class from a command line. To do this:
• Open a command prompt window (Start | Programs | Accessories | Command
Prompt)
• Change into the directory in which you have saved your BlueJ FirstJava
project – go into the project folder e.g. H:\JavaProjects\FirstJava
• To check that the Java interpreter command line will run, type java and hit
Enter (java is one of the executables that comes with the Java SDK)
• You should get a help message showing the usage for the Java command line.
• If not, there is a problem with the paths i.e. the system cannot find the java
executable – in this case, the path to the JDK bin directory needs to be added
to your path setting.
• Assuming java runs ok, now call it to run the FirstJava class – like this:
H:\JavaProjects>java FirstJava
• The class name is case-sensitive – if you type in a class name that does not
exist, you will get an error message with the first line like this:
Exception in thread "main" java.lang.NoClassDefFoundError:
• When the class runs, you should see the output on the command line, like this:
initial value of x is:0
value of x after adding 5 is: 5

1.5 Compiling a class from command line


You can also compile classes from the command line, using the javac executable.
• First, type javac at the command line to see if the system can find the
executabe.
• If it cannot find it, there may be a problem with your path settings – ask your
instructor if this is the case.
• To compile the FirstJava class from the command line, type the following:
javac FirstJava.java
• The .java file is the source code file that you have been editing in BlueJ. The
compiler creates the FirstJava.class file.
• If no errors are reported, you should have a new class file – type dir at the
command line to check that the FirstJava.class file has been updated.

1.6 Java Garbage Collection (Destroying of Ojbects)


Note that in Java, it is not necessary to explicitly destroy objects – this is done
automatically by Java itself, through a process known as garbage collection.
Basically, the interpreter keeps track of the objects and arrays it has allocated, what
local variables refer to them and references of objects and arrays to other objects and
arrays. By keeping track of this information, the interpreter can determine when an
allocated object is no longer referred to by any other object or variable. When it finds
such an object, it destroys it – because it knows this can be done safely – and thus
frees the memory resources used by the object.
The Java garbage collector runs in the background as a low-priority process – so it
does most of its work when nothing else is using the available CPU/memory
resources.

Page 8 of 11
8966468.doc FBE – Computer Science Dept

So, unlike in C and C++, the Java programmer does not have to remember to destroy
objects.
Note that there are some cases where an object uses resources that cannot be cleaned
up by the Java garbage collector e.g. open files, network connections. In these cases, a
finalizer is required for the object – created using a finalize() method. This is broadly
similar to a C++ destructor method, but not quite the same.

1.7 Static Methods and Fields


A method that is declared with the static modifier is called a class method. Likewise, a
field (variable) in a class can also be declared static – this is then called a class field.
A class method is invoked by prefixing the method name with the class name
(whereas a normal method i.e. a non-static method is invoked by prefixing the method
name with the object name). Class methods can only access class fields and class
methods – they cannot access instance fields and instance methods. Look for example
at the code in the above main method – an instance of the FirstJava class is created
and then the value of x for that object can be read. Try putting this line into the
method, before the line that creates the FirstJava object:

System.out.println ("x is " + x);

Now try to compile the class – you should get this compile error:

Non static variable x cannot be referenced from a static

context.
This is because the declaration for x does not include the static modifier, so x is an
instance field, not a class field. Main is a class method so it can only access class
fields.

1.8 Generating Documentation


• While you have a project open in BlueJ, go to the Tools menu and select
Project Documentation.
• Choose the option to Generate Documentation
• When complete, choose Tools | Project Documentation again – then choose the
option to view the documentation.
• It will open in a browser, as the docs are created as HTML files.

This documentation is created by the javadoc program that comes with the Java SDK.
It uses the comment blocks and tags in the code (@author, @param etc) to build up
the documents.
You can view the documentation for a class in BlueJ like this:
• Open the class for editing (select the class, right-click, choose Open Editor)
• In the edit window, there is a drop-down at the top right – it has two options –
Implementation and Interface
• Select Interface to show the class documentation
• Select Implementation to switch back to showing the class code

1.9 Class Diagrams on BlueJ


As you have seen by now, the BlueJ project window shows the classes you create. It
also shows relationships between the classes. The diagram for the FirstJava project

Page 9 of 11
8966468.doc FBE – Computer Science Dept

looks like that in Figure 4. The dashed line arrow indicates a 'uses' relationship –
because the SecondJava class uses an object from the FirstJava class.
When a class inherits from another class, the other type of arrow (shown in the key on
the left of the screen, under the New Class button) indicates the relationship.

Figure 4 – FirstJava project window in BlueJ – showing the relationship between the classes
You can also create relationships between classes on the diagram. To do this:
• Select the type of relationship you want - the dashed line arrow for 'uses' or
the unbroken line arrow for 'inherits'
• A prompt to select the sub-class or the class that the dependency is from (for
uses) appears in the message area at the bottom of the screen
• Select the class you want as the sub-class or as the dependent class
• A prompt appears to select the super-class or the class it depends on
• Select the class you want as the sub-class or the class that depends on the other
class
• The relationship is then created – for an inherits relationship, BlueJ will insert
the code to make the class inherit from the specified super-class; for a uses
relationship, BlueJ does not change the code as the programmer needs to
decide where it occurs.

1.10 Where to find the BlueJ Tutorial


BlueJ comes with a tutorial on how to use it, in PDF format. This tutorial is available
on the intranet.

Page 10 of 11
8966468.doc FBE – Computer Science Dept

Notes prepared by: FBE Computer Science Department.

Page 11 of 11

Вам также может понравиться