Java Reference
In-Depth Information
Declaring Classes
According to the exam objectives, you need to be able to “develop code that declares
classes.” A class is a description of an object and is one of the fundamental building blocks
of object-oriented programming. A Java class is defi ned in a .java source fi le and its
corresponding compiled bytecode is in a .class fi le. The name of the .class fi le matches
the name of the class, and the .class fi le must be saved in a directory structure that
matches the package name of the class. In this section, we discuss the elements that make
up a Java class.
A Java class can contain the following elements:
Instance variables Also referred to as fi elds, instance variables represent the attributes of
the object being described and are used to store the state of the object.
Class variables These are the static fi elds of the class and represent global variables and
data that is shared among instances of the class.
Methods The methods of a class represent the behaviors of the object being described. We
will discuss methods in detail later in this chapter.
Constructors These are special methods that get invoked during the instantiation process
and allow for the object to initialize its state.
Nested classes A Java class can contain within it the defi nition of another class. We will
discuss nested classes in detail later in this chapter.
Instance initializers These are blocks of code that execute during the instantiation
process.
Static initializers These are blocks of code that execute when the class is loaded by the
class loader.
We have already discussed instance and class variables earlier in this chapter and we will
see an example of the other elements now. Examine the ColorChanger class in Listing 2.1
and see if you can determine its instance and class variables, methods, constructors, nested
classes and instance and static initializers. The class displays a window with three buttons
in it, and clicking a button changes the background color of the window.
Listing 2.1: The ColorChanger Class
1. package com.sybex.demos;
2.
3. import java.awt.*;
4. import java.awt.event.*;
5. import static java.awt.BorderLayout.*;
6.
7. public class ColorChanger extends Frame {
Search WWH ::




Custom Search