What is a Class?

Java programs are collections of Classes. Java is an object-oriented programming language, and in object-oriented theory, a Class represents the structure of an object in the real world: an automobile, an elevator, a person, to name a few possibilities. As it runs, your program may create individual automobiles, elevators, or persons; these are called instances of objects.

But this isn’t quite true in practice. Often a Class is a collection of code used by other Classes.

HelloWorldClass

HelloWorldClass, Line by Line

Let’s examine the class we’ve created in Lesson 1.

Lines 1-3 are a comment.

/**
 * lines of code. 
 */

There are two ways to write a comment in Java:

  • A string of characters starting with “/*” and ending with “*/”, possibly spanning multiple lines of code.
  • A string of characters starting with “//” and continuing to the end of the line.

Any programming course (and this is no exception) will stress the importance of adding comments to your code to explain its purpose and methodology, and making sure they’re up-to-date across code changes. The next developer to see your code will thank you. Sometimes that developer will be yourself!

Line 4 is the package declaration.

package org.hardknockjava;

The first statement in every Java class is a declaration of its package. As we explained earlier, packages are the directory structure of a Java program, and where a given package is found in the directory structure must match this declaration. The source code files for Classes don’t have to be laid out in the same structure, although in Eclipse and other IDEs they are–and in fact, the package statement is expected to match the location of the source code containing it, and your IDE will show an error message if it does not.

Line 6 is an import declaration.

import java.util.ArrayList;

Other classes that this class refers to must be qualified in one of two ways:

  • Identified by package name each time they’re used. For example:
java.util.ArrayList myList;
  • Named in an import statement.

Line 12 is the class declaration.

public class HelloWorldClass {

Not surprisingly, every class needs a statement identifying the class. This line has four key components.

The access modifier

This lets the JVM know what other classes are able to refer to this class. There are four levels of access:

  • public: Any other class can refer to this class.
  • private: No class other than those contained within this one can refer to this class.
  • protected: Only this class, its subclasses (including those in other packages), and other classes in the same package, can refer to this class.
  • default (no modifier at all): This class, and other classes in the same package, can refer to this class.

The keyword class followed by the class identifier, or name

An opening curly brace delimiting the start of the class content. There’s a corresponding closing curly brace on line 31 delimiting the end of the class content.

Lines 13-16 are field declarations.

	private int myInteger = 1;
	long myLong;
	static boolean shouldPrint = true;
	ArrayList myList;

A field (but more familiarly, a variable) is an area in memory that holds a piece of data. A field declaration has these parts:

  • The optional word static. A field having this modifier is known as a static variable or class variable; it belongs to the class as a whole. A field without the modifier is an instance variable; there is a distinct occurrence of the field for each instance of the class (each automobile, elevator, or person, for example).
  • Like classes, fields can have access modifiers. In our example, myInteger is unknown outside this class; and the others, having no explicit access modifier, are known within the same package.
  • The field type. This specifies the kind of value the field is allowed to contain. More on this later.
  • The field identifier.
  • An optional initial value. In our example, myInteger is assigned the value 1 for each new instance of the class, and shouldPrint is assigned the value true when the class is first used.

Lines 21-26 and lines 28-30 are method declarations

In object-oriented programming, a class has two types of entities:

  • Data (that is, fields), which is information about the state of the class or an instance of the class.
  • Methods: the pieces of code that do the work.

Our class has two methods: main and greet.

Method greet(): Declaration

private void greet() {
    System.out.println("Hello world!");
}

Line 28 declares the method. Like classes and fields, it can have an access modifier. In this case, the method is private: it’s unknown outside this class.

The next word is the type of value the method will return to the method that calls it. It might be a field type like int, long, or String; but in this case the word void indicates that no value is returned.

Next is the method identifier–its name–and following that, a list of arguments in parentheses. Arguments are values passed to the method that it can use in doing its work. In this example, there are no arguments; even so, the parentheses are mandatory. Furthermore, every reference to the method must be followed by a pair of parentheses containing the arguments passed to the method; if the method has no arguments, the parentheses are still required.

Finally, the curly brace appears to delimit the start of the method.

Method greet() in Detail

Method greet has one line. Let’s examine it in detail.

    System.out.println("Hello world!");

Our method calls another method, println(), of a public static object field called out, in the class System, passing the String whose value is “Hello world!”.

The periods connecting “System”, “out”, and “println” indicate that System qualifies out (it indicates what out belongs to), and out qualifies println() (it indicates what object’s println() method is being called).

We know println is a method because it’s followed by parentheses. Method calls are always followed by parentheses, even if there be nothing inside them.

We know out is public because we were allowed to refer to it directly from within our class, HelloWorldClass. We know it’s a field (as opposed to a method) because its name isn’t followed by parentheses. We know it’s static because it’s an attribute of the System class, instead of an instance of the System class. We know it’s an object instance itself because we’re calling a method belonging to it; primitive fields don’t have methods. (System.out, by the way, represents the system console output device.)

Finally, System is a class that represents the Java Virtual Machine itself. We know it’s a class because it’s not defined anywhere within our class–and because its name is capitalized (by convention, class names are capitalized, even though the language doesn’t require it). The class System is in package java.lang, and classes in this package don’t require qualification; that’s why the name doesn’t appear as “java.lang.System” and there’s no include statement for it.

Method main()

public static void main(String[] args) {
    HelloWorldClass helloWorld = new HelloWorldClass();
    if (shouldPrint) {
        helloWorld.greet();
    }
}

You might recall that when we created this class in the editor back in Lesson 1, we chose to have the skeleton of method main() created automatically. So what’s so special about main() that it appears in the class creation dialog? It’s simply this:

main() is important because it’s where your program begins execution. You might have multiple classes with main() methods. You might start the program for production purposes in one class, and start with other classes for any purpose, such as running a recovery procedure or tests of your code. The command line with which you start execution determines the class in which execution begins, and looks like this:

java org.hardknockjava.HelloWorldClass

The program “java” is your Java Virtual Machine, and “org.hardknockjava.HelloWorldClass” is the package-qualified name of the class with whose main() method your program begins execution.

Method main() in Detail

Now let’s look at main() more closely.

public static void main(String[] args) {

The method is public so it’s visible to any other class in the Java Virtual Machine–or the JVM itself. This allows the JVM to find the main() method. It’s static because it belongs to HelloWorldClass as a whole and doesn’t pertain to only instances of the class. It’s void because it returns no value to the caller. And it accepts an array of type String, named args, as an argument. If the command line had been

java org.hardknockjava.HelloWorldClass larry moe curly

the value of args would be an array of the strings, “larry”, “moe”, and “curly”.

HelloWorldClass helloWorld = new HelloWorldClass();

The phrase “new HelloWorldClass()” creates an instance of the HelloWorldClass class and assigns it to a variable, named helloWorld, of class HelloWorldClass. This is just like a field declaration with an assignment–except that this variable cannot take an access modifier or static declaration and is known only within the main() method. The new operator is the most common means of creating an object instance.

if (shouldPrint) {
    helloWorld.greet();
}

Lastly, we have an if statement which says, “if the expression shouldPrint is true, execute the statement or group of statements that follows. And there is a “group” of statements, contained within curly braces, which runs: it invokes the greet() method of the instance helloWorld.

What You Need to Know

  • All Java code appears in classes. Classes are structured to model real-world objects, but don’t have to.
  • A Java program usually contains many classes.
  • Classes are instantiated to create individual occurrences of the class. For example, a class called Frog might be instantiated to create an individual Frog, usually with the new operator: Frog kermit = new Frog();
  • Classes describe data (called fields or variables) and operations (called methods).
  • Any given field, and any given method, is either static (i.e., not tied to any instance of the class) or not (i.e., associated with a particular instance).
  • Classes are organized into packages. The qualifiers (the words between periods) in a package name represent the directories and subdirectories in which the compiled classes will appear at deployment and, when an IDE is used, where source code appears as well. The IDE manages all this for you.
  • There are two ways of writing comments in Java. Always comment your code so readers can understand what it’s trying to accomplish and how it works.
  • At least one class in a Java program must have a main() method, with which the program will begin execution.

Continue to learn about Java Fields.