Hour 12
Java Has Class

In this hour, you will learn all about Java classes after performing some hands-on programming with the NetBeans integrated development environment (IDE). This, perhaps, is one of the heaviest hours in this 24-hour tutorial due to the nature of object-oriented programming (OOP).

Most Java programming revolves around an object’s class data and methods. Java contains all kinds of rules and conventions for specifying class data and methods. In this hour, you’ll learn how methods perform their work, and you’ll see how to set up data that responds to those methods.

The highlights of this hour include the following:

Image Working inside the NetBeans IDE

Image Displaying Java output in windows

Image Using classes to define objects

Image Understanding how methods behave

Image Passing and returning arguments

Image Overloading methods to ease programming duties

Using NetBeans to Run a Java Program

You probably don’t want to wait any longer to begin coding in Java. You’ve now got enough of the language’s background to begin with some hands-on work.

Listing 12.1 contains a Java source program that asks for two numbers and displays the sum of them. The Java source code might seem rather long for such a simple calculation; after all, a pocket calculator could do this in four button presses. The apparent wordiness of the code is because some overhead is required for Java applications, and the OOP mechanisms, such as private data members, add some code, as you’ll see throughout the last half of this hour. Fortunately, the wordiness does not increase in direct proportion to an application’s requirements.

LISTING 12.1 This simple java program adds two numbers together

public class Calculator {

    /**
      * @param args the command line arguments
      */
    public static void main (String args[]) {
    int intSum;              // holds the sum

     // compute sum
     intSum = 14 + 35;

     // show user the sum
     System.out.println("The total is " + intSum);

      System.exit(0); // stops the execution
   }
}

To create the program in Listing 12.1, just follow these steps:

  1. Start NetBeans. A startup dialog appears for a few moments, and the IDE opens with a start page displayed in the main editing window, as shown in Figure 12.1. Java programs you create with NetBeans belong to projects, so you must create one. Click the New Project button, shown in Figure 12.1.

  2. In the New Project dialog, select Java in the Categories pane and Java Application in the Projects pane; then click Next.

  3. In the Project Name field, enter FirstProject (or anything else you like). Deselect the Create Main Class box and make a note of the value in the Project Location text field. This is the place on your disk where NetBeans saves all the Java programs you put in this project.

  4. Click Finish. NetBeans creates the project and adds it to the Projects pane, which is on the left-hand side, right below the New Project button.

  5. With a project open, you’re ready to begin creating a Java program. Click New File, the button adjacent to New Project. The New File dialog opens.

    images

    FIGURE 12.1
    Creating a new project in NetBeans. (Credit: © 2017-2019 The Apache Software Foundation)

  6. Choose Java from the Categories pane and Java Main Class from File Types; then click Next. You are telling NetBeans that you want to create a standalone Java application. All Java programs use main as the starting point of the program’s execution. main is the name of a method, or routine, and some small Java programs contain only a main method. NetBeans actually builds part of the main procedure for you so that you don’t have to type the entire program in Listing 12.1.

  7. In the Class Name field, enter Calculator. This will be the name of the program.

  8. Click Finish. NetBeans builds the outline of your program, shown in Listing 12.2.

LISTING 12.2 NetBeans builds an outline of your code so you have less to type

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Greg Perry
 */
public class Calculator {

 /**
  * @param args the command line arguments
  */
 public static void main(String[] args) {
     // TODO code application logic here
  }
}

NetBeans adds several comments and uses the same syntax as C uses, which is still supported by the Java language. The compiler considers all text between an opening /* and a closing */ pair of characters, even if the words span multiple lines, to be a comment. NetBeans adds several comments to your code that begin with asterisks just to help separate the comments from executable program code. You can also use the newer-style comments that begin with //. The advantage of the old style is that in multiple lines of comments, only the first one has to begin with //.

Commented items that begin with an ampersand (@) are special commented lines supplied by NetBeans that you should replace with something other than the default values, such as your name (for example, @author). Of course, because they’re inside comments, you can put anything you want there. But as you learned in Hour 3, “Designing a Program,” maintenance is vital when a group of programmers are working together, and each programmer should put his or her name in the source code along with a version number of the code to show what was worked on. For now, you can remove these comment lines preceded by the ampersand by selecting and deleting them as you would do in a word processor.

The class name chosen for a Java program determines its filename. So, because this class is called Calculator, the filename is Calculator.java. All Java source code ends in the .java filename extension.

Within the file, NetBeans creates a method, the regular main method. The main method has the words public static void before the name to define how this method is to be viewed. These keywords basically tell the compiler that main is a public method that can be seen from the rest of the files in the project, if the project has additional files and the main method returns no values.

Values, called arguments, are placed inside main’s parentheses in order to be passed to main from other places. When your programs have multiple methods, those methods can transfer values back and forth through this argument list. main’s argument list is there in case you want to send values from the operating system to the program when the program first starts. In most cases you won’t do this, but a string array exists in the main method just in case.

Java created this program shell for you so that your only job is to fill in the source code with the rest of Listing 12.1’s code, compile the program, and see the results. To finish the program, follow these steps:

  1. Delete the comment // TODO code application logic here and at that same spot, type main’s body of code, shown in Listing 12.3.

    LISTING 12.3 Type this to complete the main procedure that NetBeans began for you

        public static void main(String args[]) {
             int intSum;          // holds the sum
    
             // compute sum
             intSum = 14 + 35;
    
             // show user the sum
             System.out.println("The total is " + intSum);
    
             System.exit(0);      // stops the execution
    }
  2. Your program should now look like the one in Listing 12.4. Although you may have changed, added, or deleted some comments, your non-comment code should exactly match that of the listing.

    LISTING 12.4 The completed version of the calculator program

        /**
         *
         * @author Greg Perry
         */
        public class Calculator {
    
           /**
            * @param args the command line arguments
            */
          public static void main(String args[]) {
               int intSum;       // holds the sum
    
               // compute sum
               intSum = 14 + 35;
    
               // show user the sum
               System.out.println("The total is " + intSum);
    
               System.exit(0); // stops the execution
            }
    }
  3. You can now run the program. NetBeans compiles the program automatically if there are no errors. To run it, press Shift+F6 or choose the menu command Run, Run File. If you don’t see the Output window, click the Output tab at the bottom of the editing window where you entered the program’s source code. The output window shows the following program result:

    The total is 49

Going GUI

You’ve successfully run your first Java program, but the output is text based and does not take advantage of a graphical environment very well. Listing 12.5 contains the same program as the previous one except for two added lines that take advantage of Swing (the precursor of JavaFX). Like JavaFX, Swing was a Java library that enables you to add message boxes, get input from input boxes, and add windowlike features to your program, among many other capabilities.

Create a new Java program following the same steps undertaken with Calculator but make SwingCalculator the class name when you’re asked for it in the New File dialog.

LISTING 12.5 Move away from text mode and into windowed features

import javax.swing.*;

/**
 *
 * @author Greg Perry
 */
public class SwingCalculator {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int intSum;     // holds the sum

       // compute sum
       intSum = 14 + 35;

       // show user the sum
      JOptionPane.showMessageDialog(null, "The total is " + intSum);

      System.exit(0); // stops the execution

    }
}

When you execute your program, the message box shown in Figure 12.2 appears. This is better and more modern than outputting straight text, isn’t it? Click the message box’s OK button to close the message box window when you’re done.

images

FIGURE 12.2
In this program, Swing powers a Java program’s graphical user interface (GUI).

The Java libraries, such as Swing and JavaFX, are full of objects you can bring into your own code and use. Part of the fun in getting to know Java is figuring out what the language can do for you through the use of these object-oriented library routines. Need to add a command button or another feature to your program? Look for an object library that supplies that feature and just plug the object into your program! This is one of the beauties of Java and OOP.

Note

The Swing object library can be used by this program because of the import command that imports, or brings into your program, all the windowlike objects from the library named javax.swing. One of the many features of this library is the JOptionPane program, which enables you to send output to a windowed message box instead of as text in a window, as you did in the previous section using System.out.println. System is actually an object, your computer, and out is a subobject, or a derived object, that represents a text window.

Java and OOP

Java is an OOP (object-oriented programming) language, and just about everything you do in it involves working with an object of some kind. An object is a place where more than one variable resides, with methods that do things to (and with) those variables. Objects give their variables special treatment, such as protecting the variables’ details from the rest of the code, but still, an object is a place where two or more variables often appear together in a group.

Consider this object declaration:

public class Employee {
    protected String firstName[15] = new String;
    protected String lastName[15] = new String;
    protected float salary;
    protected int age;
    // rest of object's declaration follows
}

Although several variables are declared here, two as arrays, they are collected together into the class called Employee. Just as the integer data type is not a variable but defines data, neither is Employee a variable; it is a class that declares what subsequent variables will look like. The class simply defines the format of an object that you generate from that class, just as the integer data type defines the format of a variable that you generate from the integer data type. The protected keyword tells Java that those members are not accessible from outside the class; that is, only code that you subsequently place inside the class can use the protected data.

Figure 12.3 shows how the Employee object’s data values appear in memory. Variables inside objects are called members, but they’re really just variables. After the variable members are defined in the object, the rest of the declaration often contains procedures called methods, which are routines that act on the object’s data.

images

FIGURE 12.3
Objects can contain lots of variables, and their data types don’t have to match.

Overview of Classes

All Java programs are actually objects themselves. An entire Java program is an object. There is a special top-level object called java.lang.Object. Your program is a derivation from that object. When you derive one object from another, or inherit an object from another, the derived object takes on all the properties of its parent object, the higher-level object.

Here is the line that derived from this special Java application object in this lesson’s earlier programs:

public class Calculator extends java.lang.Object {

In other words, you created a Java application, an object, from the java.lang.Object object. More specifically, you created a new class by inheriting from the java.lang.Object class. You extended a new object from an existing one that represented a generic Java application.

An object is more than a variable. An object is an active variable that, with its data and methods, not only has characteristics from the data values but also can perform operations on that data with its member code. As you pursue your programming career and learn more about objects, you will learn how languages such as Java specifically activate objects so that you can use those objects in other programs you write. You can reuse an object from a program that you previously wrote simply by copying the object’s class definition to your new program.

Unlike with the built-in data types, such as int, if you perform a math operation on one of your objects, you have to teach Java how to do the math by writing a method that performs the work. Once you supply the code, however, calculating with the objects is basically as easy to do as calculating with the built-in types.

Listing 12.6 demonstrates a class with data values (often called data members or just members) and methods (procedures inside the class).

LISTING 12.6 A class can have both data members and procedure methods

// The Box Class

class Box {      // a new class, so there is no
      // extension or inheritance from another class
    float area; // a class data member
    int colorCode; // a class data member

    void calcArea(float width, float length) {
      // computes a value from data passed to the object
      area = width * length;
    }

    void setColor(int colorValue) {
       // sets a color for the object
       colorCode = colorValue;
    }
}

Box is a class with four members: Two of Box’s members are data members (area and colorCode), and two are methods (calcArea() and setColor()). Box is not an object, just a definition of the object (the class). You can, however, instantiate objects from the Box class, meaning you can define object variables.

Note

Box is not a fully working, complete class. You would need to add additional members to effectively define a full class with ample data and methods.

Java does not normally know what a Box is. Only after you declare the Box class, as in Listing 12.6, can you then define (instantiate) an object like this:

Box hatHolder;    // create variable for a new object

The new variable named hatHolder is an object variable. Can you see that, loosely speaking, an object is a lot like a variable? You first have to tell Java about the object’s type by defining the object’s class, and you then have to define one or more objects, just as you can define one or more variables. Unlike a variable, however, the hatHolder objects contain more than a single data type; hatHolder is a combination int and float value, along with two methods that manipulate those data values.

If you want to execute one of the object’s methods, you only need to use the dot operator. Suppose you wanted to calculate the area of the hatHolder object. The following statement executes hatHolder’s calcArea() method:

hatHolder.calcArea(4.3, 10.244);   // executes the calcArea method

In the previous hour, you learned how to use the new keyword to declare an array. new also defines objects. Here is how you would instantiate a Box object using new:

Box hatHolder = new Box();   // instantiates a new Box object

Always use the parentheses when you use new with object instantiation. You can instantiate two Box objects as follows:

Box slot1 = new Box();
Box slot2 = new Box();

You now can calculate the area for the second Box object:

slot2.calcArea(1.0, 5.0); // sets the second object's area

You can specify the color for the first box as follows:

slot1.setColor(4); // sets the first object's color

Do You Understand OOP?

The nature of objects and OOP sneaks up on you. Relax if you don’t feel as though you’re mastering objects as quickly as you learned the non-OOP parts of the Java language, such as for loops. This is your first book of programming! Complete books much thicker than this one are devoted to the explanation of OOP concepts.

OOP requires a special kind of thinking that does not always come quickly. Throughout this hour, you’ll familiarize yourself with OOP. When you’re ready to return to OOP with Java or another OOP-based language such as C++, this introduction will pay dividends.

Methods Do the Work in Classes

Although you’ve seen methods in action, and although you know a little about what methods are all about, this section explains methods in a little more detail and fills in a few more pieces of the method puzzle.

A Method’s Execution

Methods perform work. Methods operate on class data by using the controlling statements you learned about in the previous hour and also by utilizing variables to hold data. A method’s argument list inside the method’s parentheses may contain values, or the list may be empty. If arguments exist, the code that calls the method must initialize those values and send the expected arguments and types.

Tip

Think of an argument as a variable that’s passed from one statement to a method. Arguments act like variables.

Figure 12.4 shows how the code in one method calls another method and sends that called method two arguments. Java sends a copy of the argument but does not really send the argument variables themselves. Therefore, if the called method changes an argument in any way, the change is not noticed when the calling code regains control.

Note

Java is known as a call-by-value language because a called method can never change the calling method’s argument data. The called method can use and modify the arguments within the called method’s statements, but when control returns to the calling code, the variables sent as arguments to the methods are unmodified in the calling method.

Figure 12.4’s receiving method takes two values, computes with them, prints their newly computed values, and then returns control to the calling class.

Here is the output from Figure 12.4’s code:

In method...
a=456.000
b=4608.294930876

In calling class...
a=10.0
b=20.0
images

FIGURE 12.4
The calling code sends two expected arguments to the called code.

As you can see, the called method receives two values and changes those values, but the changes last only inside the method. The calling class code’s variables are not, and cannot be, changed by the method.

The method arguments in Figure 12.4 are named x and y, even though the calling program names those variables a and b. The received names might or might not match those in the calling code because only values are passed and not variables. The biggest concern you must have when passing data to methods is to get the number of arguments and data types correct. The method is expecting a float followed by a double, as you can see from this method’s declaration line:

void myMethod(float x, double y)

The calling code must provide two variables that match this pattern. The first definition line of a called method must always declare the arguments and their data types.

The passing of data between code and methods is not strictly one way. A method can return a value to the calling code. Although you can send zero, one, or multiple arguments to a method, a method can return only one value. Figure 12.5 illustrates the return nature of methods.

images

FIGURE 12.5
A called method can return only a single value.

Here is the output from Figure 12.5’s program:

In calling class...
a=10.0
b=20.0

The doubleIt() method is a two-way method in that the calling code passes an argument, and the method also returns a value to the calling code. The called method does not change any value and returns the doubled value back to the calling code. The calling code captures the return value in the variable named doub.

If a method requires no arguments, leave the argument list empty.

Summary

You now know the basics of OOP. You should have a better idea what classes, methods, and data are all about. The new operator creates the class objects that your program can use. The object is much more than just a variable that holds data; objects contain methods, so objects are more active than variables.

The next hour takes a quick tour of Java-based web applets. You’ll see exactly how to embed a Java program inside a web page and how to set up the program to run when the user loads the page inside a web browser.

Q&A

Q. NetBeans has many options. How can I learn more about it?

A. NetBeans certainly is a comprehensive package with which you can develop many different kinds of Java programs. The online help system is complete, and Oracle’s www.netbeans.org website contains information about the IDE and all aspects of the Java language, from the programmer’s perspective as well as the user’s.

Q. If I wanted to pass arguments to main() from my operating system, how would I do that?

A. Suppose you wrote a Java program that calculated the sales commission for any salesperson in your company. You could pass the salesperson’s employee number to main(), and the program would then calculate the appropriate commission after looking up that salesperson’s sales data in the company files. Several ways exist to pass such an employee number. One way on Windows would be to place the program in your Start menu, right-click on the compiled program’s filename, select Properties, and type the number to the right of the filename. All arguments passed to the program appear to the right of the filename when you execute the file in such a way.Of course, changing the program’s properties is a tedious way to execute the program for all salespeople for whom you want to calculate commission. These command-line arguments actually were more important in the pre-Windows DOS operating system, where typing filenames to execute programs was more common. In such an application today, you would make your program more usable by forgoing the command-line arguments in favor of prompting the user for the salesperson’s employee number inside the program after the program starts.

Workshop

The quiz questions are provided for your further understanding.

Quiz

1. What alternative to using // can you use for commenting code in Java?

2. What are arguments?

3. Where does the argument list reside in the main() procedure?

4. What do Swing and JavaFX add to Java programs?

5. What command brings Java object libraries into Java programs?

6. How does a class differ from an object?

7. True or false: All Java programs derive from a single Java object named java.lang.Object.

8. What takes place when you instantiate an object?

9. What happens when you extend one object from another?

10. True or false: If an argument list requires no arguments, you should keep the argument list empty.

Answers

1. You can enclose comments in /* and */.

2. Arguments are values passed between a calling procedure and a called procedure.

3. The main() argument list is there so that users can pass arguments from the operating system environment to the program.

4. Swing and JavaFX add windowed controls to a program.

5. The import command brings Java object libraries into programs.

6. A class defines the way objects look and behave.

7. True

8. The program builds an object based on the class definition.

9. The extended object inherits the data and methods from the parent object.

10. True. You should keep the argument list empty if the argument list requires no arguments. (However, you do place void inside empty argument lists in C and C++.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.83.240