Unit 5: Your first Java class

Before you begin

This unit is part of the “Intro to Java programming” learning path. Although the concepts discussed in the individual units are standalone in nature, the hands-on component builds as you progress through the units, and I recommend that you review the prerequisites, setup, and unit details before proceeding.

Unit objectives

  • Use the Eclipse Package Explorer to create a package and declare a class
  • Add variables and methods to your class
  • Learn how the Logger class helps you keep an eye on your application’s behavior
  • Use the Eclipse code generator
  • Create a JUnit test case and run it from inside Eclipse

Your Person class

You’re about to create and work with your first Java class — the same Person class that you’ve so far examined in the abstract. The following video takes you through all of this unit’s steps. Watch first, and then I’ll recap the steps briefly in the text while giving you a closer look at the code.

Step 1: Create a package

Rather than use the default package (almost always a bad idea), create one specifically for the code you’re writing. Click File > New > Package to start the Java Package wizard. Type com.makotojava.intro into the Name text box and click Finish.

Step 2: Declare the class

Now you can see your new package in the Package Explorer. The easiest way to create a class from there is to right-click the package and choose New > Class…. In the New Class dialog box’s Name text box, type Person and then click Finish.

Eclipse generates a shell class for you and shows the source code in the edit window:

package com.makotojava.intro;

public class Person {


Optionally, tidy up your workspace by closing views that you don’t need.

Step 3: Add built-in logging

Before you do any further coding, you need to know how your programs tell you what they’re doing.

The Java platform includes the java.util.logging package, a built-in logging mechanism for gathering program information in a readable form. Loggers are named entities that you create through a static method call to the Logger class:

import java.util.logging.Logger;
Logger l = Logger.getLogger(getClass().getName());

When calling the getLogger() method, you pass it a String. For now, get in the habit of passing the name of the class that the code you’re writing is located in. From any regular (that is, nonstatic) method, the preceding code always references the name of the class and passes that to the Logger.

If you’re making a Logger call inside of a static method, reference the name of the class you’re inside of:

Logger l = Logger.getLogger(Person.class.getName());

The code you’re inside of is the Person class, so you reference a special literal called class that retrieves the Class object and gets its Name attribute. Add the logging code so that Person now looks like this:

package com.makotojava.intro;

import java.util.logging.Logger;

public class Person {

Logger l = Logger.getLogger(Person.class.getName());


Step 4: Add class variables

In Unit 4, you saw how to begin fleshing out the Person class, but I didn’t explain much of the syntax. Now you’ll learn more formally how to add class variables.

For convenience, Listing 1 repeats the Person class code that you saw in Unit 4.

Listing 1. Person class definition with a constructor

Recall that a variable has an accessSpecifieraccessSpecifier, a dataTypedataType, a variableNamevariableName, and, optionally, an initialValueinitialValue. In Unit 4, you looked briefly at how to define the accessSpecifieraccessSpecifier and variableNamevariableName.

A dataTypedataType can be either a primitive type or a reference to another object. For example, notice in Listing 1 that age is an int (a primitive type) and that name is a String (an object). The JDK comes packed full of useful classes like java.lang.String, and those in the java.lang package don’t need to be imported (a shorthand courtesy of the Java compiler). But whether the dataTypedataType is a JDK class such as String or a user-defined class, the syntax is essentially the same.

Table 1 shows the eight primitive data types you’re likely to use on a regular basis, including the default values that primitives take on if you don’t explicitly initialize a member variable’s value.

Table 1. Primitive data types
Type Size Default value Range of values
boolean n/a false true or false
byte 8 bits 0 -128 to 127
char 16 bits (unsigned) \u0000′ \u0000′ to \uffff’ or 0 to 65535
short 16 bits 0 -32768 to 32767
int 32 bits 0 -2147483648 to 2147483647
long 64 bits 0 -9223372036854775808 to 9223372036854775807
float 32 bits 0.0 1.17549435e-38 to 3.4028235e 38
double 64 bits 0.0 4.9e-324 to 1.7976931348623157e 308

Step 5: Add getters, setters, a constructor, and a main method

Back in the Eclipse source-code editor for Person, add lines 3 through 7 of the following code so that your class now looks like this:

package com.makotojava.intro;

import java.util.logging.Logger;

public class Person {

  Logger l = Logger.getLogger(Person.class.getName());

  private String name;
  private int age;
  private int height;
  private int weight;
  private String eyeColor;
  private String gender;

Eclipse has a handy code generator for generating getters and setters (among other items). Right-click the Person class in the Package Explorer and select Source > Generate Getters and Setters…. In the Generate Getters and Setters dialog box, select all of the attributes except l (which is the logger) and click OK.

Now, add a constructor to Person by typing the code from Listing 2 into your source window, just below the top part of the class definition (the line immediately beneath public class Person ()).

Listing 2. Person constructor

Make sure that you have no wavy lines indicating compile errors.

Step 6: Generate a JUnit test case

Now you can generate a JUnit test case where you instantiate a Person, using the constructor in Listing 2, and then print the state of the object to the console. In this sense, the “test” makes sure that the order of the attributes on the constructor call are correct (that is, that they’re set to the correct attributes).

In the Package Explorer, right-click your Person class and select New > JUnit Test Case. In the first page of the New JUnit Test Case wizard, accept the defaults by clicking Next. In the Test Methods dialog box — the place where you select the methods that you want the wizard to build tests for — select only the constructor and click Finish. Eclipse then generates the JUnit test case.

Open PersonTest, go into the testPerson() method, and make it look like Listing 3.

Listing 3. The testPerson() method

Step 7: Run your unit test in Eclipse

In Eclipse, right-click PersonTest.java in the Package Explore and select Run As > JUnit Test. The Console view opens automatically to show Logger output, and the JUnit view indicates that the test ran without errors.

Previous: Getting started with the Java languageNext: Adding behavior to a Java class

J Steven Perry