Last Updated:

My first Java object

Creating a Package

Switch to the Java Browsing perspective in Eclipse if you are not already in it. We're going to create the first Java class. The first step is to create a place to host the class.

Instead of using the default package, let's create one specifically for the Intro project. Select File>New>Package. This should display the Package wizard (see Figure 3).

Package Wizard

Rice. 3. Package Wizard

Enter intro.core as the package name and click Finish. In the workspace, you should see the following package as Packages:

intro.core

Notice that the icon to the left of the packet is transparent, that is, it looks like a darkened version of the package icon. This is the general convention in the Eclipse user interface to denote empty elements. Your package does not yet contain any Java classes, so the icon is dimmed.

Class Declaration

You can create a Java class in Eclipse by selecting File>New, but we'll use the toolbar instead. Look at the top of the Packages view and find tools for creating projects, packages, and classes. Click the New Java Class button (green "C") to display the New Java Class wizard. Enter Metaverse as the class name and accept all defaults by clicking Finish. You should now see a few changes:

  • The Metaverse class appears as Classes to the right of the Packages view (see Figure 4).
    Workspace

    Rice. 4. Workspace

  • The icon of the intro.core package is no longer dimmed.
  • Below these views is the editor for Metaverse.java.

Right now, the class looks like this:

package intro.core;

public class Metaverse { }

Eclipse generates a wrapper or template for the class for you and inserts the package statement at the top. So far, the body of the class is empty. We just have to add something to it. You can configure templates for new classes, methods, and so on in the Preferences wizard you used earlier (Window>Preferences). You can customize code templates in Java>Code Style>Code Templates. In fact, to make it easier to display the code, I'm going to remove all comments from the templates, that is, all the following lines: starting with comments , surrounded by /* comments */ , surrounded by /** comments */ . From now on, you won't see any comments in the code until we specifically discuss their application, which will be done in the next section.

But before we go any further, let's demonstrate a way to work in the Eclipse IDE that makes life easier. In the editor, change the word class to clas and wait a few seconds. Notice that Eclipse will underline it with a red wavy line. If you place the mouse pointer over it, Eclipse displays an information window warning you that there is a syntax error. Eclipse helps you by periodically compiling your code and unobtrusively alerting you when a problem exists. If you were using the javac command-line tool, you would have to compile the code first and wait for the error to appear. This can greatly slow down the development process. Eclipse fixes this issue.

Comments

Like most other programming languages, Java supports comments, which are simple strings that the compiler ignores when checking syntax. Java supports several comment options:

One-line comment. The compiler ignores any text that follows two forward slashes.
/* Comment in a few lines. The compiler ignores any text between the asterisks. */
/** Javadoc-style comment. The compiler ignores the text between the asterisks, and the javadoc program
uses it. */

The last option is the most interesting. In a nutshell, javadoc is a program that comes with the Java SDK distribution that can help you generate an HTML document for your code. You can generate documentation for your own classes that looks almost identical to the interactive Java API documentation. If you comment out your code appropriately, you can run the javadoc program from the command line. You can find instructions and all available information on javadoc on the Java Technology Web site.

Reserved words

There is another topic that we should consider before starting to write code that the compiler will check. There are some words in the Java language that you can't use when naming your variables. Here is a list of them:

 abstract boolean break byte
 case catch char class
 const continue char class
 default do double else
 extend false final finally
 float for goto if
 implements import int instanceof
 interface long int native
 new null package private
 protected public package private
 static strictfp super switch
 synchronized short super this
 throw throws true try
 transient return void volatile
 while assert true false
 null   

It's not a very large list, and Eclipse displays reserved words in bold as you type them, so you don't even have to memorize them. All but the last three words are Java keywords. The last three words are reserved words. For our purposes, there is no difference between the two; you can't use either.

Now a little real code.

Add variables

As I said earlier, a copy of Metaverse knows its name, age, nationality, and gender. We can add this data to our Metaverse class by declaring it as variables. Then each instance of the Metaverse class will contain them. Most likely, each instance of Metaverse will have different values for these variables. This is why the variables of each object are often referred to as instance variables—they are different for each instance of the class. Let's add them using the protected keyword as an access specifier:

Now each instance of Metaverse will contain this data. Note that each line of code ends with a semicolon. This is a requirement of the Java language. Also note that each variable has a data type. We have one integer and three string variables. The data types for variables can be of two varieties:

  • Primitive data types.
  • Objects (either user-defined or internal to the Java language), also known as reference variables.

Primitive Data Types

There are nine primitive types of data that you are likely to encounter regularly:

Type

Size

Default value

Example

 booleanN/A false true
 byte8 bits 0 2
 char16 bits ‘u/0000’ ‘a’
 short16 bits 0 12
 int32 bits 0 123
 long64 bits 0 9999999
 float32 bits with decimal point 0.0 123.45
 double64 bit with decimal point 0.0 999999999.99999999

We used int for the age variable because we don't need decimal values, and the int type is large enough to store any real age of the person. We used String for the other three variables because they are not digital. String is a class from the java.lang package that you can access automatically in your Java code at any time (we'll talk more about this in the Strings section). You can also declare a user-defined variable type, such as Metaverse.

We've defined each variable on a separate line, but it's not necessary. If you have two or more variables of the same type, you can define them on a single line by separating them with commas, for example:

If we wanted to initialize these variables when we declare them, we could simply add an initialization after each variable name:

Now our class knows about itself, and we can prove it, which we will do in the next section.

Main() method

There is a special method that you can include in any class so that the JRE can execute code. It's called main(). Each class can have only one main() method. Of course, not every class will have it, but since Metaverse is the only class we have so far, let's add the main() method to it so that we can create an instance of the Metaverse class and check its instance variables:

In the body of the main() method, we created an instance of the Metaverse class, and then printed out the values of the instance variables. Look at the first line. This is a situation where proponents of object-oriented code criticize the Java language. They say that new should be an Metaverse method, and you should call it like this: Metaverse.new(). I certainly accept their point of view, but the Java language doesn't work that way, and this is one of the cases where PLO proponents can rightly claim that it's not pure object-oriented code. Look at the first line again. Remember that every Java class has a default constructor, which is what we used here.

After creating an Metaverse instance, we store it in a local variable called myMetaverse. Then print out the values of its instance variables. In almost every programming language, you can print something to a console. The Java language is no exception. In Java, you do this by calling the println() method of the out stream of the System object. Don't worry about not understanding the details of the process yet. Just know that we are using a helper method to output information. In each call, we pass a string of characters and connect it to the value of the myMetaverse instance variable. We'll look at this method in detail later.

Running Code in Eclipse

There's only a little left for you to do in Eclipse to run this code. Select the Metaverse class in the Types view and click on the "running man" icon in the toolbar. A Run dialog box should appear that will allow you to create a configuration to run your program. Select Java Application as the type of configuration you want to create and click New. Eclipse will specify "Metaverse" as the default name for the configuration, which is appropriate for us. Click Run to view the results. Eclipse displays a Console view below the code editor; it should look something like Figure 5.

Results of the program

Rice. 5. Results of the program

Note that the variables contained their default values. By default, each variable in an instance of a user-defined or built-in type is null. It's almost always a good idea to explicitly initialize variables, especially for objects, so you know what values they contain. Go back and initialize these variables with the following values:

VariableMeaning
 name «Bob»
 age 25
 race «inuit»
 gender «male»

Run the code again by clicking on the "running man" icon. You should see the new values on your console.

Now let's make our Metaverse object able to tell other objects about their data.