1.1. The structures of a Java class and a source code file

[1.2] Define the structure of a Java class

Note

When you see a certification objective callout such as the preceding one, it means that in this section we’ll cover this objective. The same objective may be covered in more than one section in this chapter or in other chapters.

This section covers the structures and components of both a Java source code file (.java file) and a Java class (defined using the keyword class). It also covers the differences between a Java source code file and a Java class.

First things first. Start your exam preparation with a clear understanding of what’s required from you in the certification exam. For example, try to answer the following query from a certification aspirant: “I come across the term ‘class’ with different meanings: class Person, the Java source code file (Person.java), and Java bytecode stored in Person.class. Which of these structures is on the exam?” To answer this question, take a look at figure 1.1, which includes the class Person, the files Person.java and Person.class, and the relationship between them.

Figure 1.1. Relationship between the class file Person and the files Person.java and Person.class and how one transforms into another

As you can see in figure 1.1, a person can be defined as a class Person. This class should reside in a Java source code file (Person.java). Using this Java source code file, the Java compiler (javac.exe on Windows or javac on Mac OS X/Linux/UNIX) generates bytecode (compiled code for the Java Virtual Machine) and stores it in Person.class. The scope of this exam objective is limited to Java classes (class Person) and Java source code files (Person.java).

1.1.1. Structure of a Java class

The OCA Java SE 8 Programmer I exam will question you on the structure and components of a Java source file and the classes or interfaces that you can define in it. Figure 1.2 shows the components of a Java class file (interfaces are covered in detail in chapter 6).

Figure 1.2. Components of a Java class

In this section, I’ll discuss all Java class file components. Let’s get started with the package statement.

Note

The code in this book doesn’t include a lot of spaces—it imitates the kind of code that you’ll see on the exam. But when you work on real projects, I strongly recommend that you use spaces or comments to make your code readable.

package statement

All Java classes are part of a package. A Java class can be explicitly defined in a named package; otherwise, it becomes part of a default package, which doesn’t have a name.

A package statement is used to explicitly define which package a class is in. If a class includes a package statement, it must be the first statement in the class definition:

Note

Packages are covered in detail in section 1.3 of this chapter.

The package statement can’t appear within a class declaration or after the class declaration. The following code will fail to compile:

The following code will also fail to compile, because it places the package statement within the class definition:

Also, if present, the package statement must appear exactly once in a class. The following code won’t compile:

import statement

Classes and interfaces in the same package can use each other without prefixing their names with the package name. But to use a class or an interface from another package, you must use its fully qualified name, that is, packageName.anySubpackageName.ClassName. For example, the fully qualified name of class String is java.lang.String. Because using fully qualified names can be tedious and can make your code difficult to read, you can use the import statement to use the simple name of a class or interface in your code.

Let’s look at this using an example class, AnnualExam, which is defined in the package university. Class AnnualExam is associated with the class certification.ExamQuestion, as shown using the Unified Modeling Language (UML) class diagram in figure 1.3.

Figure 1.3. UML representation of the relationship between class AnnualExam and ExamQuestion

Note

A UML class diagram represents the static view of an application. It shows entities like packages, classes, interfaces, and their attributes (fields and methods) and also depicts the relationships between them. It shows which classes and interfaces are defined in a package. It depicts the inheritance relationship between classes and interfaces. It can also depict the associations between them—when a class or an interface defines an attribute of another type. All UML representations in this chapter are class diagrams. The exam doesn’t cover UML diagrams. But using these quick and simple diagrams simplifies the relationship between Java entities—both on the exam and in your real-world projects.

Note

Throughout this book, bold font will be used to indicate specific parts of code that we’re discussing, or changes or modifications in code.

Here’s the code for class AnnualExam:

Note that the import statement follows the package statement but precedes the class declaration. What happens if the class AnnualExam isn’t defined in a package? Will there be any change in the code if the classes AnnualExam and ExamQuestion are related, as depicted in figure 1.4?

Figure 1.4. Relationship between the packageless class AnnualExam and ExamQuestion

In this case, the class AnnualExam isn’t part of an explicit package, but the class ExamQuestion is part of the package certification. Here’s the code for the class AnnualExam:

As you can see in the previous example code, the class AnnualExam doesn’t define the package statement, but it defines the import statement to import the class certification.ExamQuestion.

If a package statement is present in a class, the import statement must follow the package statement. It’s important to maintain the order of the occurrence of the package and import statements. Reversing this order will result in your code failing to compile:

We’ll discuss import statements in detail in section 1.3 of this chapter.

Comments

You can also add comments to your Java code. Comments can appear at multiple places in a class. A comment can appear before and after a package statement, before and after the class definition, as well as before and within and after a method definition. Comments come in two flavors: multiline comments and end-of-line comments.

Multiline comments span multiple lines of code. They start with /* and end with */. Here’s an example:

Multiline comments can contain special characters. Here’s an example:

In the preceding code, the comments don’t start with an asterisk on every line. But most of the time when you see a multiline comment in a Java source code file (.java file), you’ll notice that it uses an asterisk (*) to start the comment in the next line. Please note that this isn’t required—it’s done more for aesthetic reasons. Here’s an example:

End-of-line comments start with // and, as evident by their name, they’re placed at the end of a line of code or on a blank line. The text between // and the end of the line is treated as a comment, which you’d normally use to briefly describe the line of code. Here’s an example:

Though usage of multiline comments in the following code is uncommon, the exam expects you to know that the code is valid:

Here’s what happens if you include multiline comments within quotes while assigning a string value:

When included within double quotes, multiline comments are treated as regular characters and not as comments. So the following code won’t compile because the value assigned to variable name is an unclosed string literal value:

In the earlier section on the package statement, you read that a package statement, if present, should be the first line of code in a class. The only exception to this rule is the presence of comments. A comment can precede a package statement. The following code defines a package statement, with multiline and end-of-line comments:

Line defines an end-of-line code comment within multiline code. This is acceptable. The end-of-line code comment is treated as part of the multiline comment, not as a separate end-of-line comment. Lines and define end-of-line code comments. Line defines an end-of-line code comment at the start of a line, after the class definition.

The multiline comment is placed before the package statement, which is acceptable because comments can appear anywhere in your code.

Javadoc comments

Javadoc comments are special comments that start with /** and end with */ in a Java source file. These comments are processed by Javadoc, a JDK tool, to generate API documentation for your Java source code files. To see it in action, compare the API documentation of the class String and its source code file (String.java).

Class declaration

The class declaration marks the start of a class. It can be as simple as the keyword class followed by the name of a class:

The declaration of a class is composed of the following parts:

  • Access modifiers
  • Nonaccess modifiers
  • Class name
  • Name of the base class, if the class is extending another class
  • All implemented interfaces, if the class is implementing any interfaces
  • Class body (class fields, methods, constructors), included within a pair of curly braces, {}

Don’t worry if you don’t understand this material at this point. We’ll go through these details as we move through the exam preparation.

Let’s look at the components of a class declaration using an example:

public final class Runner extends Person implements Athlete {}

The components of the preceding class declaration can be illustrated as shown in figure 1.5.

Figure 1.5. Components of a class declaration

Table 1.1 summarizes the compulsory and optional components.

Table 1.1. Components of a class declaration

Mandatory

Optional

Keyword class Access modifier, such as public
Name of the class Nonaccess modifier, such as final
Class body, marked by the opening and closing curly braces, {} Keyword extends together with the name of the base class
  Keyword implements together with the names of the interfaces being implemented

We’ll discuss the access and nonaccess modifiers in detail in sections 1.4 and 1.5 in this chapter.

Class definition

A class is a design used to specify the attributes and behavior of an object. The attributes of an object are implemented using variables, and the behavior is implemented using methods. For example, consider a class as being like the design or specification of a mobile phone, and a mobile phone as being an object of that design. The same design can be used to create multiple mobile phones, just as the Java Virtual Machine (JVM) uses a class to create its objects. You can also consider a class as being like a mold that you can use to create meaningful and useful objects. A class is a design from which an object can be created.

Let’s define a simple class to represent a mobile phone:

class Phone {
    String model;
    String company;
    Phone(String model) {
        this.model = model;
    }
    double weight;
    void makeCall(String number) {
        // code
    }
    void receiveCall() {
        // code
    }
}

Points to remember:

  • A class name starts with the keyword class. Watch out for the case of the keyword class. Java is cAsE-sEnSiTivE. class (lowercase c) isn’t the same as Class (uppercase C). You can’t use the word Class (uppercase C) to define a class.
  • The state of a class is defined using attributes or instance variables.
  • It isn’t compulsory to define all attributes of a class before defining its methods (the variable weight is defined after Phone’s constructor). But this is far from being optimal for readability.
  • The behavior is defined using methods, which may include method parameters.
  • A class definition may also include comments and constructors.
Note

A class is a design from which an object can be created.

Variables

Revisit the definition of the class Phone in the previous example. Because the variables model, company, and weight are used to store the state of an object (also called an instance), they’re called instance variables or instance attributes. Each object has its own copy of the instance variables. If you change the value of an instance variable for an object, the value for the same named instance variable won’t change for another object. The instance variables are defined within a class but outside all methods in a class.

A single copy of a class variable or static variable is shared by all the objects of a class. The static variables are covered in section 1.5.3 with a detailed discussion of the nonaccess modifier static.

Methods

Again, revisit the previous example. The methods makeCall and receiveCall are instance methods, which are generally used to manipulate the instance variables.

A class method or static method can be used to manipulate the static variables, as discussed in detail in section 1.5.3.

Constructors

Class Phone in the previous example defines a single constructor. A class constructor is used to create and initialize the objects of a class. A class can define multiple constructors that accept different sets of method parameters.

1.1.2. Structure and components of a Java source code file

A Java source code file is used to define Java entities such as a class, interface, enum, and annotation.

Note

Java annotations are not on the exam and so won’t be discussed in this book.

All your Java code should be defined in Java source code files (text files whose names end with .java). The exam covers the following aspects of the structure of a Java source code file:

  • Definition of a class and an interface in a Java source code file
  • Definition of single or multiple classes and interfaces within the same Java source code file
  • Application of import and package statements to all the classes in a Java source code file

We’ve already covered the detailed structure and definition of classes in section 1.1.1. Let’s get started with the definition of an interface.

Definition of an interface in a Java source code file

An interface specifies a contract for the classes to implement. You can compare implementing an interface to signing a contract. An interface is a grouping of related methods and constants. Prior to Java 8, interface methods were implicitly abstract. But starting with Java version 8, the methods in an interface can define a default implementation. With Java 8, interfaces can also define static methods.

Here’s a quick example to help you understand the essence of interfaces. No matter which brand of television each of us has, every television provides the common functionality of changing the channel and adjusting the volume. You can compare the controls of a television set to an interface and the design of a television set to a class that implements the interface controls.

Let’s define this interface:

interface Controls {
    void changeChannel(int channelNumber);
    void increaseVolume();
    void decreaseVolume();
}

The definition of an interface starts with the keyword interface. Remember, Java is case-sensitive, so you can’t use the word Interface (with a capital I) to define an interface. This section provides a brief overview of interfaces. You’ll work with interfaces in detail in chapter 6.

Definition of single and multiple classes in a single Java source code file

You can define either a single class or an interface in a Java source code file or multiple such entities. Let’s start with a simple example: a Java source code file called Single-Class.java that defines a single class SingleClass:

Here’s an example of a Java source code file, Multiple1.java, that defines multiple interfaces:

You can also define a combination of classes and interfaces in the same Java source code file. Here’s an example:

No particular order is required to define multiple classes or interfaces in a single Java source code file.

Exam Tip

The classes and interfaces can be defined in any order of occurrence in a Java source code file.

When you define a public class or an interface in a Java source file, the names of the class or interface and Java source file must match. Also, a source code file can’t define more than one public class or interface. If you try to do so, your code won’t compile, which leads to a small hands-on exercise for you that I call Twist in the Tale, as mentioned in the preface. The answers to all these exercises are provided in the appendix.

About the Twist in the Tale exercises

For these exercises, I’ve tried to use modified code from the examples already covered in the chapter. The Twist in the Tale title refers to modified or tweaked code.

These exercises will help you understand how even small code modifications can change the behavior of your code. They should also encourage you to carefully examine all the code in the exam. The reason for these exercises is that in the exam, you may be asked more than one question that seems to require the same answer. But on closer inspection, you’ll realize that the questions differ slightly, and this will change the behavior of the code and the correct answer option!

Twist in the Tale 1.1

Modify the contents of the Java source code file Multiple.java, and define a public interface in it. Execute the code and see how this modification affects your code.

Question: Examine the following content of Java source code file Multiple.java and select the correct options:

// Contents of Multiple.java
public interface Printable {
    //.. we are not detailing this part
}
interface Movable {
    //.. we are not detailing this part
}

Options:

  1. A Java source code file can’t define multiple interfaces.
  2. A Java source code file can only define multiple classes.
  3. A Java source code file can define multiple interfaces and classes.
  4. The previous class will fail to compile.

If you need help getting your system set up to write Java, refer to Oracle’s “Getting Started” tutorial, http://docs.oracle.com/javase/tutorial/getStarted/.

Twist in the Tale 1.2

Question: Examine the content of the following Java source code file, Multiple2.java, and select the correct option(s):

// contents of Multiple2.java
interface Printable {
    //.. we are not detailing this part
}
class MyClass {
    //.. we are not detailing this part
}
interface Movable {
    //.. we are not detailing this part
}
public class Car {
    //.. we are not detailing this part
}
public interface Multiple2 {}

Options:

  1. The code fails to compile.
  2. The code compiles successfully.
  3. Removing the definition of class Car will compile the code.
  4. Changing class Car to a nonpublic class will compile the code.
  5. Changing interface Multiple2 to a nonpublic interface will compile the code.
Application of package and import statements in Java source code files

In the previous section, I mentioned that you can define multiple classes and interfaces in the same Java source code file. When you use a package or import statement within such Java files, both the package and import statements apply to all the classes and interfaces defined in that source code file.

For example, if you include a package and an import statement in Java source code file Multiple.java (as in the following code), Car, Movable, and Printable will be become part of the same package com.manning.code:

Exam Tip

Classes and interfaces defined in the same Java source code file can’t be defined in separate packages. Classes and interfaces imported using the import statement are available to all the classes and interfaces defined in the same Java source code file.

In the next section, you’ll create executable Java applications—classes that are used to define an entry point of execution for a Java application.

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

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