In general, class declarations can include these components, in order:
- Modifiers such as public, private, and a number of others that you will encounter later.
- The class name, with the initial letter capitalized by convention.
- The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
- A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class canimplement more than one interface.
- The class body, surrounded by braces, {}.
More generally, method declarations have six components, in order:
- Modifiers—such as
public
,private
, and others you will learn about later. - The return type—the data type of the value returned by the method, or
void
if the method does not return a value. - The method name—the rules for field names apply to method names as well, but the convention is a little different.
- The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses,
()
. If there are no parameters, you must use empty parentheses. - An exception list—to be discussed later.
- The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.
Object
, which
does
have a no-argument constructor.
Not all combinations of instance and class variables and methods are allowed:
- Instance methods can access instance variables and instance methods directly.
- Instance methods can access class variables and class methods directly.
- Class methods can access class variables and class methods directly.
- Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the
this
keyword as there is no instance forthis
to refer to.