Java Reference
In-Depth Information
Class Declaration #2
class
Welcome {
}
Class Declaration #3
class Welcome {
}
This topic uses the following class declaration format: the opening brace is placed on the same line following the
class name, and the closing brace is placed on a separate line and it is aligned with the first character of the first line
of the class declaration, like so:
class Welcome {
}
The body of a class consists of four parts. All parts are optional, may appear in any order, and can be split into
multiple sections, not all together.
Field Declarations
Initializers: Static initializers and instance initializers
Constructors
Method Declarations
Java language does not impose any order in which the four parts of the body of a class may appear. I will start
with method declarations and confine the discussion only to simple method declarations in this chapter. I will discuss
advanced aspects of method declarations and other parts of class body declarations in the chapter on classes and
objects.
Let's discuss how to declare a method for a class. You might guess that the method declaration would begin
with a keyword method , as package and class declarations began with the keywords package and class , respectively.
However, a method declaration does not begin with a keyword method . In fact, method is not a keyword in Java
language. You begin a class declaration with the keyword class indicating that you are going to declare a class.
However, in case of a method declaration, the first thing you specify is the type of value that a method will return to
its caller. If a method does not return anything to its caller, you must mention that fact in the beginning of the method
declaration, so you use the keyword void to indicate that a method does not return anything. The name of the method
follows the return type of the method, and left and right parentheses follow the method name. Like a class, a method
has a body part, which is enclosed in braces. The simplest method declaration in Java looks like the following:
<<MethodReturnType>> <<MethodName>> (<<arguments>>) {
// Body of the method goes here
}
The following is an example of a method declaration:
void main() {
// Empty body of the main method
}
 
Search WWH ::




Custom Search