Chairperson and Program Coordinator for the Computer Science Technology Program at Dawson College Instructor and Program Consultant for the School of Extended Learning Computer Institute at Concordia University I have been passionate about programming since buying an Apple][+ in 1980. I paid the extra $450 to bring the RAM up to 48K! Ken has posted 15 posts at DZone. You can read more from them at their website. View Full User Profile

NetBeans in the Classroom: Mandatory Methods for Beans (Part 1)

07.01.2014
| 1681 views |
  • submit to reddit
Ken Fogel is the Program Coordinator and Chairperson of the Computer Science Technology program at Dawson College in Montreal, Canada. He is also a Program Consultant to and part-time instructor in the Computer Institute of Concordia University's School of Extended Learning. He blogs at omniprogrammer.com and tweets @omniprof. His regular columns about NetBeans in education are listed here.

There are two types of textbooks that cross my desk for teaching Java. One is called early objects and the other is called late objects. Many times it is two versions of the same book. If you have read some of my previous articles you will discover that I am an "objects on day one" instructor. That is why I have my students create beans for data right after we go over the primitive data types. That is also why I no longer use a textbook in my first level course.

In my first level class, I introduce my students to the first two of the five methods that every data bean should have. The first method is the constructor. Its purpose is to set the initial state of an object. NetBeans makes this easy with the menu Source -> Insert Code feature. We used it in the previous article to create the getters and setters. Now we will use it for the constructor.

By tradition, the constructor is usually placed right after the class variables. I place my cursor on a blank line just after the last variable and have NetBeans create the constructor.

A dialog appears to select which class variables to include in the constructor. Leaving them all unchecked creates a default or no-args constructor that is responsible for its own initial state. Checking one or more will create a constructor that allows the object to have its state set by the creator of the object. As new programmers just starting out I tell my students to create both a default constructor and a non-default constructor with all the class variables selected. This means they do this task twice.

This results in the following code:

public MyCarBean() {
}

public MyCarBean(String manufacturer, String model, int engineDisplacement,
        int cylinders, String transmission, String driveTrain, int weight,
        double cityConsumptionInLitres, double cityConsumptionInMilesPerGallon,
        double highwayConsumptionInLitres, double highwayConsumptionInMilesPerGallon,
        double estimatedAnnualFuelCost) {
    this.manufacturer = manufacturer;
    this.model = model;
    this.engineDisplacement = engineDisplacement;
    this.cylinders = cylinders;
    this.transmission = transmission;
    this.driveTrain = driveTrain;
    this.weight = weight;
    this.cityConsumptionInLitres = cityConsumptionInLitres;
    this.cityConsumptionInMilesPerGallon = cityConsumptionInMilesPerGallon;
    this.highwayConsumptionInLitres = highwayConsumptionInLitres;
    this.highwayConsumptionInMilesPerGallon = highwayConsumptionInMilesPerGallon;
    this.estimatedAnnualFuelCost = estimatedAnnualFuelCost;
}

If an object is created without any arguments, the default constructor is invoked and the class variables take on the default values.  For primitives this is zero and for object references this is null. Essentially any class variable that is not initialized explicitly will be implicitly initialized to these values.

Java also allows you to initialize class variables where they are declared.

public class Employee {
    private double wage = 10.0;
    private SkillSet skill = new SkillSet();

I tell my students that I will accept a simple assignment such as wage = 10 but not the creation of an object with new. For this you need a constructor.

public class Employee {
    private double wage = 10;
    private SkillSet skill;

    public Employee() {
        super();
        skill = new SkillSet();
        }

You will also notice the explicit call to the super class constructor with super(). A lot has been written on this subject. My approach for new students to Java programming is to require an explicit call to the default constructor. It can do no harm but should you use super() and this is an error because the class you are extending does not have a default constructor then this tells you something important about what you are extending. What that is will be the subject of an upcoming article. My students write super() as the first line of every constructor they write.

With the two constructors out of the way the next mandatory method is toString(). This is a method that is inherited by every object you create from the super class at the top of the class hierarchy called Object. This method allows you to use a reference to an object in places where a String reference is expected. Normally the state of every class variable is appended to a String so that it can be used in a System.out.println statement.

Just as you created the constructors you can create the toString method. Select Source -> Insert Code and then select toString(). The traditional location for toString is after the last method in the bean.

The next dialog allows you to choose which fields to include in the toString method. The defaults are to use them all and that is what I tell my students to do.

The resulting code looks like:

@Override
public String toString() {
    return "MyCarBean{" + 
       "manufacturer=" + manufacturer + 
       ", model=" + model + 
       ", engineDisplacement=" + engineDisplacement + 
       ", cylinders=" + cylinders + 
       ", transmission=" + transmission + 
       ", driveTrain=" + driveTrain + 
       ", weight=" + weight + 
       ", cityConsumptionInLitres=" + cityConsumptionInLitres + 
       ", cityConsumptionInMilesPerGallon=" + cityConsumptionInMilesPerGallon + 
       ", highwayConsumptionInLitres=" + highwayConsumptionInLitres + 
       ", highwayConsumptionInMilesPerGallon=" + highwayConsumptionInMilesPerGallon + 
       ", estimatedAnnualFuelCost=" + estimatedAnnualFuelCost + '}';
}

In my initial assignments I require my students to produce reports consisting of all the members of the class. I show my students how to dress up toString for this purpose.

@Override
public String toString() {
   return "                       Manufacturer = " + manufacturer + 
        "\n                              Model = " + model + 
        "\n                Engine Displacement = " + engineDisplacement + 
        "\n                          Cylinders = " + cylinders + 
        "\n                       Transmission = " + transmission + 
        "\n                        Drive Train = " + driveTrain + 
        "\n                             Weight = " + weight + 
        "\n   City Consumption In Litres/100km = " + cityConsumptionInLitres + 
        "\n            City Consumption In MPG = " + cityConsumptionInMilesPerGallon + 
        "\nHighway Consumption In Litres/100km = " + highwayConsumptionInLitres + 
        "\n         Highway Consumption In MPG = " + highwayConsumptionInMilesPerGallon + 
        "\n         Estimated Annual Fuel Cost = " + estimatedAnnualFuelCost + "\n";
}

My next article will look at the final three mandatory methods.

Published at DZone with permission of its author, Ken Fogel.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)