Lesson 3 | Class declarations |
Objective | Learn about class and interface declarations. |
Java Class Declarations
In order to write object-oriented code using Java, you need to be able to declare and use classes. Classes are declared using the following syntax:
class ClassName {
// Class body
}
This declares a class named ClassName
that is a subclass of Object
. To declare a class that is a subclass of another class (named SuperClass
) you use the extends
clause:
class ClassName extends SuperClass {
// Class body
}
An interface defines methods that are provided by those classes that implement the interface.
To specify that a class implements one or more interfaces, you use the implements
clause:
class ClassName
extends SuperClass implements
Interface1, Interface2 {
// Class body
}
By stating that
ClassName
implements
Interface1
and
Interface2
we require
ClassName
to provide an implementation of all the methods defined in
Interface1
and
Interface2
.
A class may specify the optional modifiers
public
,
abstract
, and
final
.
These are placed before the class declaration. A
public
class may be accessed outside the package in which it is declared. An
abstract
class is a class that is incomplete in the sense that it may declare one or more
abstract methods[1]. A
final
class identifies a class that may not be extended by a subclass. A class may not be both
final
and
abstract
. The following declares a
public
and
final
class:
final class
The following class is a final class that cannot be extended.
public final class ClassName {
// Class body
}
The class body
The class body declares
members[2] (field variables and methods), constructors, and initializers. Class members may also be inner classes or inner interfaces. Class members and initializers are covered in Module 5.
[1]
Abstract method: A method whose implementation is deferred to a subclass.
[2]
Member: An element of a class or interface, such as a field variable, method, or inner class. An element of a package, such as a class, interface, or subpackage.