Classes

A class is a blueprint or template to create objects of identical type. If you have an Employee class, you can create any number of Employee objects. To create Street objects, you need a Street class. A class determines what kind of object you get. For example, if you create an Employee class that has age and position fields, all Employee objects created out of this Employee class will have age and position fields as well. No more no less. The class determines the object.

In summary, classes enable programmers to create the abstraction of a problem.

In OOP, abstraction is the act of using programming objects to represent real-world objects. As such, programming objects do not need to have the details of real-world objects. For instance, if an Employee object in a payroll application needs only be able to work and receive a salary, then the Employee class needs only two methods, work and receiveSalary. OOP abstraction ignores the fact that a real-world employee can do many other things including eat, run, kiss and kick.

Classes are the fundamental building blocks of a Java program. All program elements in Java must reside in a class, even if you are writing a simple program that does not require Java’s object-oriented features. A Java beginner needs to consider three things when writing a class:

  • the class name
  • the fields
  • the methods

There are other things that can be present in a class, but they will be discussed later.

A class declaration must use the keyword class followed by a class name. Also, a class has a body within braces. Here is a general syntax for a class:

class className {
    [class body]
}

For example, Listing 4.1 shows a Java class named Employee, where the lines in bold are the class body.

Listing 4.1: The Employee class

class Employee {
    int age;
    double salary;
}

Note:

By convention, class names capitalize the initial of each word. For example, here are some names that follow the convention: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator. This type of naming convention is known as Pascal naming convention. The other convention, the camel naming convention, capitalize the initial of each word, except the first word. Method and field names use the camel naming convention.

A public class definition must be saved in a file that has the same name as the class name, even though this restriction does not apply to non-public classes. The file name must have java extension.

Note

In UML class diagrams, a class is represented by a rectangle that consists of three parts: the topmost part is the class name, the middle part is the list of fields, and the bottom part is the list of methods. (See Figure 4.1) The fields and methods can be hidden if showing them is not important.

Figure 4.1: The Employee class in the UML class diagram

Fields

Fields are variables. They can be primitives or references to objects. For example, the Employee class in Listing 4.1 has two fields, age and salary.

However, a field can also refer to another object. For instance, an Empoyee class may have an address field of type Address, which is a class that represents a street address:

Address address;

In other words, an object can contain other objects, that is if the class of the former contains variables that reference to the latter.

Field names should follow the camel naming convention. The initial of each word in the field, except for the first word, is written with a capital letter. For example, here are some “good” field names: age, maxAge, address, validAddress, numberOfRows.

Methods

A methods defines an action that a class’s objects (or instances) can perform. A method has a declaration part and a body. The declaration part consists of a return value, the method name and a list of arguments. The body contains code that performs the action.

To declare a method, use the following syntax:

returnType methodName (listOfArguments)

The return type of a method can be a primitive, an object or void. The return type void means that the method returns nothing. The declaration part of a method is also called the signature of the method.

For example, here is a method named getSalary that returns a double.

double getSalary()

The getSalary method does not accept arguments.

As another example, here is a method that returns an Address object.

Address getAddress()

And, here is a method that accepts an argument:

int negate(int number)

If a method takes more than one argument, two arguments are separated by a comma. For example, the following add method takes two ints and return an int.

int add(int a, int b)

The Method main **

A special method called main provides the entry point to an application. An application normally has many classes and only one of the classes needs to have a main method. This method allows the containing class to be invoked.

The signature of the main method is as follows.

public static void main(String[] args)

If you wonder why there is “public static void” before main, you will get the answer towards the end of this section.

You can pass arguments to main when using java to run a class. To pass arguments, type them after the class name. Two arguments are separated by a space.

java className arg1 arg2 arg3 ...

All arguments must be passed as strings. For instance, to pass two arguments, “1” and “safeMode” when running a Test class, type this:

java Test 1 safeMode

Constructors

Every class must have at least one constructor. Otherwise, no objects could be created out of it and the class would be useless. As such, if your class does not explicitly define a constructor, the compiler adds one for you.

A constructor is used to construct an object. A constructor looks like a method and is sometimes called a constructor method. However, unlike a method, a constructor does not have a return value, not even void. Additionally, a constructor must have the same name as the class.

The syntax for a constructor is as follows.

constructorName (listOfArguments) {
    [constructor body]
}

A constructor may have zero argument, in which case it is called a no-argument (or no-arg, for short) constructor. Constructor arguments can be used to initialize the fields in the object.

If the Java compiler adds a no-arg constructor to a class because the class contains no constructor, the addition will be implicit, i.e. it will not be displayed in the source file. However, if there is a constructor in a class definition, regardless of the number of arguments it accepts, no constructor will be added to the class by the compiler.

As an example, Listing 4.2 adds two constructors to the Employee class in Listing 4.1.

Listing 4.2: The Employee class with constructors

public class Employee {
    public int age;
    public double salary;
    public Employee() {
    }
    public Employee(int ageValue, double salaryValue) {
        age = ageValue;
        salary = salaryValue;
    }
}

The second constructor is particularly useful. Without it, to assign values to age and position, you would need to write extra lines of code to initialize the fields:

employee.age = 20;
employee.salary = 90000.00;

With the second constructor, you can pass the values at the same time you create an object.

new Employee(20, 90000.00);

The new keyword is new to you, but you will learn how to use it later in this section.

Varargs **

Varargs is a Java feature that allows methods to have a variable length of argument list. Here is an example of a method called average that accepts any number of ints and calculates their average.

public double average(int... args)

The ellipsis says that there is zero or more arguments of this type. For example, the following code calls average with two and three ints.

double avg1 = average(100, 1010);
double avg2 = average(10, 100, 1000);

If an argument list contains both fixed arguments (arguments that must exist) and variable arguments, the variable arguments must come last.

Class Members in UML Class Diagrams

Figure 4.1 depicts a class in a UML class diagram. The diagram provides a quick summary of all fields and methods. You could do more in UML. UML allows you to include field types and method signatures. For example, Figure 4.2 presents a Book class with five fields and one method.

Figure 4.2: Including class member information in a class diagram

Note that in a UML class diagram a field and its type is separated by a colon. A method’s argument list is presented in parentheses and its return type is written after a colon.