Logger
class to keep an eye on your application's behavior, and
also how to use a main()
method as a test harness. Creating a package
If you're not already there, get to the Package Explorer view (in the Java perspective) in Eclipse through Window > Perspective > Open Perspective. You're going to get set up to create your first Java class. The first step is to create a place for the class to live. Packages are namespace constructs, and they also conveniently map directly to the file system's directory structure.Rather than use the default package (almost always a bad idea), you create one specifically for the code you are writing. Click File > New > Package to start the Java Package wizard, shown in Figure 4:
Figure 4. The Eclipse Java Package wizard
Typecom.makotojava.intro
into the Name text box and click
Finish. You'll see the new package created in the Package
Explorer. Declaring the class
You can create a class from the Package Explorer in more than one way, but the easiest way is to right-click the package you just created and choose New > Class.... The New Class dialog box opens.In the Name text box, type
Person
and then click
Finish. The new class is displayed in your edit window. I recommend closing a few of the views (Problems, Javadoc, and others) that open by default in the Java Perspective the first time you open it to make it easier to see your source code. (Eclipse remembers that you don't want to see those views the next time you open Eclipse and go to the Java perspective.) Figure 5 shows a workspace with the essential views open.
Figure 5. A well-ordered workspace
Eclipse generates a shell class for you and includes thepackage
statement at the top. You just need to flesh out the class now. You can configure
how Eclipse generates new classes through Window > Preferences > Java
> Code Style > Code Templates. For simplicity, go with Eclipse's
out-of-the-box code generation. In Figure 5, notice the asterisk (*) next to the new source-code file name, indicating that I've made a modification. And notice that the code is unsaved. Next, notice that I made a mistake when declaring the
Name
attribute: I declared Name
's type to be Strin
. The
compiler could not find a reference to such a class and flagged it as a compile
error (that's the wavy red line underneath Strin
). Of course, I can fix
my mistake by adding a g
to the end of Strin
. This is a
small demonstration of the power of using an IDE instead of command-line tools for
software development. Go ahead and correct the error by changing the type to
String
. Adding class variables
In Listing 3, you began to flesh out thePerson
class, but I didn't explain much of the syntax. Now, I formally define how to add
class variables. Recall that a variable has an
accessSpecifier
, a
dataType
, a variableName
, and,
optionally, an initialValue
. Earlier, you looked briefly at
how to define the accessSpecifier
and
variableName
. Now, you see the
dataType
that a variable can have. A
dataType
can be either a primitive type or a reference to
another object. For example, notice 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 do not need to be imported (a shorthand
courtesy of the Java compiler). But whether the dataType
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 see on a regular basis, including the default values that primitives take on if you do not 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 |
Built-in logging
Before going further into coding, you need to know how your programs tell you what they are 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:
1
2
3
| import java.util.logging.Logger; //... Logger l = Logger.getLogger(getClass().getName()); |
getLogger()
method, you pass it a String
.
For now, just 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 are making a
Logger
call inside of a static method, reference
the name of the class you're inside of:
1
| Logger l = Logger.getLogger(Person.class.getName()); |
Person
class, so you
reference a special literal called class
that retrieves the
Class
object (more on this later) and gets its Name
attribute. This tutorial's "Writing good Java code" section includes a tip on how not to do logging.
Before we get into the meat of testing, first go into the Eclipse source-code editor for
Person
and add this code just after public class Person
{
from Listing 3 so that it looks like this:
1
2
3
4
5
6
7
8
9
10
| package com.makotojava.intro; public class Person { private String name; private int age; private int height; private int weight; private String eyeColor; private String gender; } |
Person
class definition (that is, on the word Person
in the class definition) and click Source > Generate Getters and
Setters.... When the dialog box opens, click Select
All, as shown in Figure 6. Figure 6. Eclipse generating getters and setters
For the insertion point, choose Last member and click OK.Now, add a constructor to
Person
by typing the code from Listing 5 into
your source window just below the top part of the class definition (the line
immediately beneath public class Person ()
).
Listing 5. Person
constructor
1
2
3
4
5
6
7
8
| public Person(String name, int age, int height, int weight, String eyeColor, String gender) { this.name = name; this.age = age; this.height = height; this.weight = weight; this.eyeColor = eyeColor; this.gender = gender; } |
Generate a JUnit test case
Now you generate a JUnit test case where you instantiate aPerson
,
using the constructor in Listing 5, 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 are set to the correct
attributes). In the Package Explorer, right-click your
Person
class and then click
New > JUnit Test Case. The first page of the New JUnit Test
Case wizard opens, as shown in Figure 7. Figure 7. Creating a JUnit test case
Accept the defaults by clicking Next. You see the Test Methods dialog box, shown in Figure 8.Figure 8. Select methods for the wizard to generate test cases
In this dialog box, you select the method or methods that you want the wizard to build tests for. In this case, select just the constructor, as shown in Figure 8. Click Finish, and Eclipse generates the JUnit test case.Next, open
PersonTest
, go into the testPerson()
method,
and make it look like Listing 6.
Listing 6. The testPerson()
method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| @Test public void testPerson() { Person p = new Person("Joe Q Author", 42, 173, 82, "Brown", "MALE"); Logger l = Logger.getLogger(Person.class.getName()); l.info("Name: " + p.getName()); l.info("Age:" + p.getAge()); l.info("Height (cm):" + p.getHeight()); l.info("Weight (kg):" + p.getWeight()); l.info("Eye Color:" + p.getEyeColor()); l.info("Gender:" + p.getGender()); assertEquals("Joe Q Author", p.getName()); assertEquals(42, p.getAge()); assertEquals(173, p.getHeight()); assertEquals(82, p.getWeight()); assertEquals("Brown", p.getEyeColor()); assertEquals("MALE", p.getGender()); } |
Logger
class for now. Just enter the code as you
see it in Listing 6. You're now ready to run your first Java
program (and JUnit test case). Executing code in Eclipse
To run a Java application from inside Eclipse, select the class you want to run, then click the Run icon (which is green and has a small triangular arrow pointing to the right). Eclipse is smart enough to recognize that the class you want to run is a JUnit test case, and so it launches JUnit. Now, sit back and watch it go. Figure 9 shows what happens.
Figure 9. See Person
run
The Console view opens automatically and shows Logger
output. The JUnit
view also opens to show the results of the test.
0 comments:
Post a Comment