Sunday, May 28, 2017

Introduction to Java programming, Part-1 (7)

Your first Java class


It's a great opportunity to pull together what you've realized in the past segments and begin keeping in touch with some code. This area strolls you through proclaiming a class and adding factors and strategies to it utilizing the Eclipse Package Explorer. You figure out how to utilize the Logger class to watch out for your application's conduct, and furthermore how to utilize a fundamental() technique as a test bridle.

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

Type com.makotojava.intro into the Name text box and click Finish. You can 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 the package 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 the Person class, but I didn't explain much of the syntax. Now, I'll 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.
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
TypeSizeDefault valueRange of values
booleann/afalsetrue or false
byte8 bits0-128 to 127
char16 bits(unsigned)\u0000' \u0000' to \uffff' or 0 to 65535
short16 bits0-32768 to 32767
int32 bits0-2147483648 to 2147483647
long64 bits0-9223372036854775808 to 9223372036854775807
float32 bits0.01.17549435e-38 to 3.4028235e+38
double64 bits0.04.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());
When calling the 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:
Logger l = Logger.getLogger(Person.class.getName());
In this example, the code you're inside of is the Person class, so you reference a special literal called classthat 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;
}
Eclipse has a handy code generator to generate getters and setters (among other things). To try out the code generator, put your mouse caret on the 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;
}
Make sure that you have no wavy lines indicating compile errors.

Generate a JUnit test case

Now you generate a JUnit test case where you instantiate a Person, 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());
}
Don't worry about the 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).

Running your unit test in Eclipse

In Eclipse, right-click PersonTest.java in the Package Explore and select Run As > JUnit Test. Figure 9 shows what happens.
Figure 9. See Person run

The Console view opens automatically to show Logger output, and the JUnit view indicates that the test ran without errors.
Previous Post
Next Post

post written by:

0 coment�rios: