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 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
true
, false
, and null
are
technically not reserved words. Although they are literals, I included them in this
list because you can't use them to name Java constructs. One advantage of programming with an IDE is that it can use syntax coloring for reserved words, as I show later in this tutorial.
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, and at runtime, your application creates an instance of the object. An object has a crisp 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| 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 */ } |
Note: In Listing 1 and some other code examples in this section, square brackets indicate that the constructs within them are not required. The brackets themselves (unlike
{
and }
)
are not part of the Java syntax. Comments in code
Notice that Listing 1 also includes some comment lines:
1
2
3
4
5
| // This is a comment /* This is a comment too */ /* This is a multiline comment */ |
/*
, must be terminated with */
, and can span any
number of lines. You learn more about comments when you get to this tutorial's "Writing good Java code" section.
Packaging classes
With the Java language, you can choose the names for your classes, such asAccount
, Person
, or LizardMan
. At times,
you might end up using the same name to express two slightly different concepts.
This situation is called a name collision, and it 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.
Package definition
To define a package, you use thepackage
keyword followed by a legal
package name, terminated with a semicolon. Often package names are separated by dots
and follow this de facto standard scheme:
1
| package orgType.orgName.appName.compName; |
orgType
is the organization type, such ascom
,org
, ornet
.orgName
is the name of the organization's domain, such asmakotojava
,oracle
, oribm
.appName
is the name of the application, abbreviated.compName
is the name of the component.
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:
1
| import ClassNameToImport; |
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:
1
| import com.makotojava.*; |
Class declaration
To define an object in the Java language, you must declare a class. Again, think of a class as a template for an object, like a cookie cutter.Listing 1 includes this class declaration:
1
2
3
4
5
6
7
8
9
| accessSpecifier class ClassName { accessSpecifier dataType variableName [= initialValue]; accessSpecifier ClassName([argumentList]) { constructorStatement(s) } accessSpecifier returnType methodName([argumentList]) { methodStatement(s) } } |
accessSpecifier
can have several values, but usually
it is public
. You look at other values of
accessSpecifier
soon. Class-naming conventions
You can name classes pretty much however you want, but the convention is to use camel case: Start with an uppercase letter, capitalize the first letter of each concatenated word, 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.Classes can have two types of members: variables and methods.
Variables
The values of a given 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
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.
dataType
depends on what the variable is —
it might be a primitive type or another class type (again, more about this later). The
variableName
is up to you, but by convention, variable
names use the camel case convention I described in "Class-naming conventions," 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
Before moving on to methods, 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
1
2
3
4
5
6
7
8
9
10
| 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; } |
Person
isn't useful at this point,
because it defines only its attributes (and private ones at that). To be more interesting, the
Person
class needs behavior — and
that means methods. Methods
A class's methods define its behavior.Methods fall into two main categories: constructors or all other methods, of which there are 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
Next, you look in more detail at the two types of methods, 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; here it is again:
1
2
3
| accessSpecifier ClassName([argumentList]) { constructorStatement(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, you pass an
argumentList
, which is one or more of:
1
| argumentType argumentName |
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, you see what happens when you add the capability to create aPerson
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| 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; } } |
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
disambiguate the reference. 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 section and continues throughout the tutorial.Back in Listing 1, I showed you how to declare a method:
1
2
3
| accessSpecifier returnType methodName ([argumentList]) { methodStatement(s) } |
- Start with a lowercase letter.
- Avoid numbers unless they are absolutely necessary.
- Use only alphabetic characters.
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| 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... } |
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 are dependent on the state of a specific object instance for their behavior. Static methods are also sometimes called class methods, because their behavior is not 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 this tutorial, you 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 called 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:
1
| Logger l = Logger.getLogger("NewLogger"); |
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.
0 comments:
Post a Comment