Java Reference
In-Depth Information
Understand new
Understand garbage collection and finalizers
Use the this keyword
B efore you can go much further in your study of Java, you need to learn about the class.
The class is the essence of Java. It is the foundation upon which the entire Java language
is built because the class defines the nature of an object. As such, the class forms the basis
for object-oriented programming in Java. Within a class are defined data and code that acts
upon that data. The code is contained in methods. Because classes, objects, and methods
are fundamental to Java, they are introduced in this chapter. Having a basic understanding
of these features will allow you to write more sophisticated programs and better understand
certain key Java elements described in the following chapter.
Class Fundamentals
Since all Java program activity occurs within a class, we have been using classes since the
start of this topic. Of course, only extremely simple classes have been used, and we have
not taken advantage of the majority of their features. As you will see, classes are substan-
tially more powerful than the limited ones presented so far.
Let's begin by reviewing the basics. A class is a template that defines the form of an ob-
ject. It specifies both the data and the code that will operate on that data. Java uses a class
specification to construct objects . Objects are instances of a class. Thus, a class is essen-
tially a set of plans that specify how to build an object. It is important to be clear on one
issue: a class is a logical abstraction. It is not until an object of that class has been created
that a physical representation of that class exists in memory.
One other point: Recall that the methods and variables that constitute a class are called
members of the class. The data members are also referred to as instance variables .
The General Form of a Class
When you define a class, you declare its exact form and nature. You do this by specifying
the instance variables that it contains and the methods that operate on them. Although
very simple classes might contain only methods or only instance variables, most real-world
classes contain both.
A class is created by using the keyword class . A simplified general form of a class defin-
ition is shown here:
Search WWH ::




Custom Search