1.8. Creating a Java Class

Problem

You want to create a new Java class in an existing Java project.

Solution

When you have the Java perspective open and have a Java project selected in the Package Explorer, you can create new classes in Eclipse in several ways. You can use the toolbar item with the circled C icon, you can select File New Class, or you can right-click a project in the Package Explorer and select New Class in the context menu. All these methods open the New Java Class dialog.

Discussion

The New Java Class dialog is shown in Figure 1-9.

Creating a new Java class

Figure 1-9. Creating a new Java class

Over the previous few recipes, we’ve been developing a short Java project, FirstApp. Now we’re going to use the following code to display a message in that project:

public class FirstApp
{
  public static void main(String[] args)
  {
    System.out.println("Stay cool.");
  }
}

Creating Java classes is a fundamental skill for most Eclipse developers, so I’m going to cover the basics here. Note the options in this dialog: you can set a class’s access specifier as public, private, or protected; you can make the class abstract or final; you can specify the new class’s superclass (java.lang.Object is the default); and you can specify which, if any, interfaces it implements. Class creation is covered in more detail in Chapter 3.

In this book, you’ll put examples into Java packages to avoid any conflict with other code; here, we use packages named after the example’s chapter, such as org.cookbook.ch01. Enter the name of this new class, FirstApp, in the Name box and the name of a new package for this class, org.cookbook.ch01, in the Package box. Note in particular that under the question in this dialog “Which method stubs would you like to create?” that we’re leaving the checkbox marked “public static void main(String[] args)” checked. Doing so means that Eclipse will create an empty main method automatically. Click Finish to accept the other defaults.

This creates and opens the new class, FirstApp, as shown in Figure 1-10. Open the FirstApp project in the Package Explorer, and double-click the FirstApp.java entry under the org.cookbook.ch01 entry to open the new code.

Opening a Java class in Eclipse

Figure 1-10. Opening a Java class in Eclipse

You can see the code the JDT has already written in this figurenote the package statement that creates the org.cookbook.ch01 package. You also can see the main method Eclipse has added to our class. This new class will be stored in its own file, FirstApp.java, in the Eclipse folder workspace\FirstApp.

At this point, simply enter the code for this class directly in the editor and you’re set. You also can use Eclipse’s code assist to make things easier, as covered in the next recipe.

Get Eclipse Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.