Creating a New Java Class

When NetBeans creates a new project, it sets up all the necessary files and folders and creates the main class. Figure A.3 shows the first class in your project, Spartacus.java, open in the source editor.

Figure A.3. The NetBeans source editor.

Image

Spartacus.java is a bare-bones Java class that consists only of a main() method. All the light gray lines in the class are comments that exist to explain the purpose and function of the class. Comments are ignored when the class is run.

To make the new class do something, add the following line of code on a new line right below the comment // TODO code application logic here:

System.out.println("I am Spartacus!");

The method System.out.println() displays a string of text, in this case the sentence “I am Spartacus!”

Make sure to enter this exactly as it appears. As you type, the source editor figures out what you’re doing and pops up helpful information related to the System class, the out instance variable, and the println() method. You’ll love this stuff later, but for now try your best to ignore it.

After you make sure you typed the line correctly and ended it with a semicolon, click the Save All Files toolbar button to save the class.

Java classes must be compiled into executable bytecode before you can run them. NetBeans tries to compile classes automatically. You also can manually compile this class in two ways:

• Choose the menu command Run, Compile File.

• Right-click Spartacus.java in the Project pane to open a pop-up menu, and choose Compile File.

If NetBeans doesn’t allow you to choose either of these options, that means it already has compiled the class automatically.

If the class does not compile successfully, a red exclamation point appears next to the filename Spartacus.java in the Project pane. To fix the error, compare what you’ve typed in the text editor to the full source code of Spartacus.java in Listing A.1 and save the file again.

Listing A.1. The Java Class Spartacus.java


 1: /*
 2:  * To change this template, choose Tools | Templates
 3:  * and open the template in the editor.
 4:  */
 5:
 6: /**
 7:  *
 8:  * @author User
 9:  */
10: public class Spartacus {
11:
12:     /**
13:      * @param args the command line arguments
14:      */
15:     public static void main(String[] args) {
16:         // TODO code application logic here
17:         System.out.println("I am Spartacus!");
18:
19:     }
20:
21: }


The class is defined in lines 10–21. Lines 1–9 are comments included by NetBeans in every new class

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

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