Java Reference
In-Depth Information
The program in Figure 1.6 contains a single class (see the An Introduction to
Classes and Objects sidebar) named HelloWorld. Within HelloWorld is one
method: main(). The main() method is declared as public, static, and void,
which are Java keywords that are discussed later in the topic. The main()
method is unique because it is the method invoked by the JVM when this pro-
gram is executed.
The main() method must look like:
public static void main(String [] args)
An Introduction to Classes and Objects
You should understand two important object-oriented terms: object and class. A class is a
description of an object, and an object is an instance of a class.
In Java, you write classes. Because Java is purely object oriented, all of the statements
in your Java programs appear inside a Java class. Notice that the Hello, World program in
Figure 1.6 is a public class. We will discuss public in detail later, but for now I will just say
that almost every class you write in Java will be declared public.
The purpose of a class is to describe an object. An object is just what the word means
in English: a thing, an item, a noun. For example, a car, a house, an employee of a com-
pany, a window that opens on the computer screen, or a TCP/IP socket connection
between two computers.
An object consists of two major components: attributes and behaviors. The attributes of
an object are what the object consists of, and the behaviors of the object are what the
object does.
You do not write an object in object-oriented programming (OOP); you instantiate one.
You get to describe what an object will look like when it gets instantiated by defining the
attributes and behaviors of the object in a class. My favorite analogy when explaining
classes and objects is to compare blueprints to a class. A blueprint of a house tells you what
the house will look like when it is built, but it is clearly not a house—just a description of
one. When a contractor follows the blueprints and actually builds an instance of a house,
that house is an object.
How many houses can you build from a set of blueprints? As many as you want. How
many instances of a class (that is, objects) can you create? As many as you want.
A class contains the attributes and behaviors of the object it is describing. In the Hel-
loWorld class in Figure 1.10, there are no attributes and only one behavior, main(). By the
way, the behaviors are often referred to as methods, and HelloWorld contains a single
method: main().
What is interesting (and often confusing) about the HelloWorld example is that it is not
object oriented in any way. But just because our HelloWorld program does not use any
OOP concepts, we still need to write a class because the Java language requires all meth-
ods to appear within a class.
Search WWH ::




Custom Search