Contents


Unit 4: Getting started with the Java language

Find out how Java objects are structured

Comments

Before you begin

This unit is part of the "Intro to Java programming" course. Although the concepts discussed in the individual units are standalone in nature, the hands-on component builds as you progress through the units, and I recommend that you review the prerequisites, setup, and unit details before proceeding.

Unit objectives

  • Recognize the reserved words in the Java language
  • Understand the relationship between a Java class and a Java object
  • Know the function and syntax for each construct within a Java class

OOP is all about objects. This unit covers two topics specifically related to how the Java language handles objects: reserved words and the structure of a Java class.

Reserved words

Like any programming language, the Java language designates certain words that the compiler recognizes as special. For that reason, you're not allowed to use them for naming your Java constructs. The list of reserved words (also called keywords) is surprisingly short:

abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while

You also may not use true, false, and null (technically, literals rather than keywords) to name Java constructs

One advantage of programming with an IDE is that it can use syntax coloring for reserved words, as you'll see later.

Structure of a Java class

A class is a blueprint for a discrete entity (object) that contains attributes and behavior. The class defines the object's basic structure; at runtime, your application creates an instance of the object. An object has a well-defined boundary and a state, and it can do things when correctly asked. Every object-oriented language has rules about how to define a class.

In the Java language, classes are defined as shown in Listing 1:

Listing 1. Class definition
package packageName;
import ClassNameToImport; 
accessSpecifier class ClassName {
  accessSpecifier dataType variableName [= initialValue];
  accessSpecifier ClassName([argumentList]) {
    constructorStatement(s)
  }
  accessSpecifier returnType methodName ([argumentList]) {
    methodStatement(s)
  }
  // This is a comment
  /* This is a comment too */
  /* This is a
     multiline
     comment */
}

Listing 1 contains various types of constructs, including package in line 1, import in line 2, and class in line 3. Those three constructs are in the list of reserved words, so they must be exactly what they are in Listing 1. The names that I've given the other constructs in Listing 1 describe the concepts that they represent.

Notice that lines 11 through 15 in Listing 1 are comment lines. In most programming languages, programmers can add comments to help document the code. Java syntax allows for both single-line and multiline comments:

// This is a comment
/* This is a comment too */
/* This is a
multiline
comment */

A single-line comment must be contained on one line, although you can use adjacent single-line comments to form a block. A multiline comment begins with /*, must be terminated with */, and can span any number of lines.

Next, I'll walk you through the constructs in Listing 1 in detail, starting with package.

Packaging classes

With the Java language, you can choose the names for your classes, such as Account, Person, or LizardMan. At times, you might end up using the same name to express two slightly different concepts. This situation, called a name collision, happens frequently. The Java language uses packages to resolve these conflicts.

A Java package is a mechanism for providing a namespace— an area inside of which names are unique, but outside of which they might not be. To identify a construct uniquely, you must fully qualify it by including its namespace.

Packages also give you a nice way to build more-complex applications with discrete units of functionality.

To define a package, use the package keyword followed by a legal package name, ending with a semicolon. Often package names follow this de facto standard scheme:

package  orgType.orgName.appName.compName;

This package definition breaks down as:

  • orgType is the organization type, such as com, org, or net.
  • orgName is the name of the organization's domain, such as makotojava, oracle, or ibm.
  • appName is the name of the application, abbreviated.
  • compName is the name of the component.

You'll use this convention throughout this course, and I recommend that you keep using it to define all of your Java classes in packages. (The Java language doesn't force you to follow this package convention. You don't need to specify a package at all, in which case all of your classes must have unique names and are in the default package.)

Import statements

Up next in the class definition (referring back to Listing 1) is the import statement. An import statement tells the Java compiler where to find classes that you reference inside of your code. Any nontrivial class uses other classes for some functionality, and the import statement is how you tell the Java compiler about them.

An import statement usually looks like this:

import ClassNameToImport;

You specify the import keyword, followed by the class that you want to import, followed by a semicolon. The class name should be fully qualified, meaning that it should include its package.

To import all classes within a package, you can put .* after the package name. For example, this statement imports every class in the com.makotojava package:

import com.makotojava.*;

Importing an entire package can make your code less readable, however, so I recommend that you import only the classes that you need, using their fully qualified names.

Class declaration

To define an object in the Java language, you must declare a class. Think of a class as a template for an object, like a cookie cutter.

Listing 1 includes this class declaration:

accessSpecifier class ClassName {
  accessSpecifier dataType variableName [= initialValue];
    accessSpecifier ClassName([argumentList]) {
    constructorStatement(s)
  }
  accessSpecifier returnType methodName([argumentList]) {
    methodStatement(s)
  }
}

A class's accessSpecifier can have several values, but usually it's public. You'll look at other values of accessSpecifier soon.

You can name classes pretty much however you want, but the convention is to use camel case: Start with an uppercase letter, put the first letter of each concatenated word in uppercase, and make all the other letters lowercase. Class names should contain only letters and numbers. Sticking to these guidelines ensures that your code is more accessible to other developers who are following the same conventions.

Variables and methods

Classes can have two types of membersvariables and methods.

Variables

The values of a class's variables distinguish each instance of that class and define its state. These values are often referred to as instance variables. A variable has:

  • An accessSpecifier
  • A dataType
  • A variableName
  • Optionally, an initialValue

The possible accessSpecifier values are:

  • public: Any object in any package can see the variable. (Don't ever use this value; see the Public variables sidebar.)
  • protected: Any object defined in the same package, or a subclass (defined in any package), can see the variable.
  • No specifier (also called friendly or package private access): Only objects whose classes are defined in the same package can see the variable.
  • private: Only the class containing the variable can see it.

A variable's dataType depends on what the variable is — it might be a primitive type or another class type (more about this later).

The variableName is up to you, but by convention, variable names use the camel case convention, except that they begin with a lowercase letter. (This style is sometimes called lower camel case.)

Don't worry about the initialValue for now; just know that you can initialize an instance variable when you declare it. (Otherwise, the compiler generates a default for you that is set when the class is instantiated.)

Example: Class definition for Person

Here's an example that summarizes what you've learned so far. Listing 2 is a class definition for Person.

Listing 2. Basic class definition for Person
package com.makotojava.intro;

public class Person {
   private String name;
   private int age;
   private int height;
   private int weight;
   private String eyeColor;
   private String gender;
}

This basic class definition for Person isn't useful at this point, because it defines only Person's attributes (and private ones at that). To be more complete, the Person class needs behavior — and that means methods.

Methods

A class's methods define its behavior.

Methods fall into two main categories: constructors; and all other methods, which come in many types. A constructor method is used only to create an instance of a class. Other types of methods can be used for virtually any application behavior.

The class definition back in Listing 1 shows the way to define the structure of a method, which includes elements like:

  • accessSpecifier
  • returnType
  • methodName
  • argumentList

The combination of these structural elements in a method's definition is called the method's signature.

Now take a closer look at the two method categories, starting with constructors.

Constructor methods

You use constructors to specify how to instantiate a class. Listing 1 shows the constructor-declaration syntax in abstract form, and here it is again:

accessSpecifier ClassName([argumentList]) {
  constructorStatement(s)
}

A constructor's accessSpecifier is the same as for variables. The name of the constructor must match the name of the class. So if you call your class Person, the name of the constructor must also be Person.

For any constructor other than the default constructor (see the Constructors are optional sidebar), you pass an argumentList, which is one or more of:

argumentType argumentName

Arguments in an argumentList are separated by commas, and no two arguments can have the same name. argumentType is either a primitive type or another class type (the same as with variable types).

Class definition with a constructor

Now, see what happens when you add the capability to create a Person object in two ways: by using a no-arg constructor and by initializing a partial list of attributes.

Listing 3 shows how to create constructors and also how to use argumentList:

Listing 3. Person class definition with a constructor
package com.makotojava.intro;
public class Person {
  private String name;
  private int age;
  private int height;
  private int  weight;
  private String eyeColor;

  private String gender;
  public Person() {
    // Nothing to do...
  }

  public Person(String name, int age, int height, int weight String eyeColor, String gender) {
    this.name = name;
    this.age = age;
    this.height = height;
    this.weight = weight;
    this.eyeColor = eyeColor;
    this.gender = gender;
  }
}

Note the use of the this keyword in making the variable assignments in Listing 3. The this keyword is Java shorthand for "this object," and you must use it when you reference two variables with the same name. In this case, age is both a constructor parameter and a class variable, so the this keyword helps the compiler to tell which is which.

The Person object is getting more interesting, but it needs more behavior. And for that, you need more methods.

Other methods

A constructor is a particular kind of method with a particular function. Similarly, many other types of methods perform particular functions in Java programs. Exploration of other method types begins in this unit and continues throughout the course.

Back in Listing 1, you saw how to declare a method:

accessSpecifier returnType methodName ([argumentList]) {
  methodStatement(s)
}

Other methods look much like constructors, with a couple of exceptions. First, you can name other methods whatever you like (though, of course, certain rules apply). I recommend the following conventions:

  • Start with a lowercase letter.
  • Avoid numbers unless they are absolutely necessary.
  • Use only alphabetic characters.

Second, unlike constructors, other methods have an optional return type.

Person's other methods

Armed with this basic information, you can see in Listing 4 what happens when you add a few more methods to the Person object. (I've omitted constructors for brevity.)

Listing 4. Person with a few new methods
package com.makotojava.intro;

public class Person {
   private String name;
   private int age;
   private int height;
   private int  weight;
   private String eyeColor;
   private String gender;

   public String getName() { return name; }
   public void setName(String value) { name = value; }
   // Other getter/setter combinations...
}

Notice the comment in Listing 4 about "getter/setter combinations." You'll work more with getters and setters later. For now, all you need to know is that a getter is a method for retrieving the value of an attribute, and a setter is a method for modifying that value. Listing 4 shows only one getter/setter combination (for the Name attribute), but you can define more in a similar fashion.

Note in Listing 4 that if a method doesn't return a value, you must tell the compiler by specifying the void return type in its signature.

Static and instance methods

Generally, two types of (nonconstructor) methods are used: instance methods and static methods. Instance methods depend on the state of a specific object instance for their behavior. Static methods are also sometimes called class methods, because their behavior isn't dependent on any single object's state. A static method's behavior happens at the class level.

Static methods are used largely for utility; you can think of them as being global methods (à la C) while keeping the code for the method with the class that defines it.

For example, throughout the coming units, you'll use the JDK Logger class to output information to the console. To create a Logger class instance, you don't instantiate a Logger class; instead, you invoke a static method named getLogger().

The syntax for invoking a static method on a class is different from the syntax used to invoke a method on an object. You also use the name of the class that contains the static method, as shown in this invocation:

Logger l = Logger.getLogger("NewLogger");

In this example, Logger is the name of the class, and getLogger(...) is the name of the method. So to invoke a static method, you don't need an object instance, just the name of the class.

Test your understanding

  1. What are import statements used for?
    1. They serve no real purpose other than to alert other programmers to your class dependencies, as a courtesy.
    2. They are used for web software to connect to certain sites and download relevant code.
    3. They are used to tell the compiler about which classes your class references.
    4. None of the above
  2. If you want a variable to be visible only within the class that defines it, what accessSpecifier should you give it?
    1. public
    2. private
    3. None, because this is the compiler's default accessSpecifier
    4. protected
    5. None of the above
  3. What are reserved words in the Java language?
    1. Certain words or phrases that are reserved for the Java runtime, so the compiler strips them out before compiling your code.
    2. Words (also known as keywords) that you may not use to name your constructs, and that have special meaning in the Java language.
    3. There's no such thing as a "reserved word" in the Java language.
    4. Certain words that are ignored by the compiler, sort of like comments.
    5. None of the above.
  4. A package is used as a way to create an area (called a namespace) in which names are unique but outside of which they might not be.
    1. It depends on the compiler context.
    2. False
    3. There is no such thing as a "package" in the Java language.
    4. True
    5. None of the above
  5. Listing 4 adds several attributes to the Person class. As an exercise, write the getter/setter code to access/set those values. Use the getName()/setName() methods as an example.
  6. In Listing 3, an alternative constructor is also defined, along with the no-arg constructor, even though the no-arg constructor does nothing. Why might you declare the no-arg constructor in this scenario?
    1. If you don't define the no-arg constructor in every class, you'll get a compiler error.
    2. Providing the no-arg constructor allows you to create an empty Person object whose attributes are set to default values.
    3. The code in Listing 3 is in error. It won't compile because you cannot have two constructors on the same class.
    4. There's no such thing as a no-arg constructor. This is a trick question.
    5. None of the above
  7. What's the difference between static methods and instance methods?
    1. There is virtually no difference between the two.
    2. A static method can be called from any language, whereas instance methods are only allowed in a single object.
    3. Invoking an instance method on an object requires a reference to the object, whereas invoking a static method does not.
    4. A static method "sticks" to the object it is defined on, whereas an instance method can float from one object to another.

Check your answers.

For further exploration

The Java Language Specification

Java Language Basics

Classes and Objects

Java in a Nutshell, 6th Edition by Benjamin J. Evans and David Flanagan

Java: A Beginner's Guide, 6th Edition by Herbert Schildt

IBM Code: Java journeys

Previous: Object-oriented concepts and principlesNext: Your first Java class


Downloadable resources


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java development
ArticleID=1036605
ArticleTitle=Unit 4: Getting started with the Java language
publish-date=09142016