Java Reference
In-Depth Information
Chapter 6
Classes and Objects
In this chapter, you will learn:
•
What classes are in Java
•
How to declare classes in Java
•
How to declare class members such as fields and methods and their access levels
•
How to create objects of a class
•
How to declare import statements in a compilation unit
this
and
super
in a Java program
•
The meaning of the pronouns
•
Different parameter passing mechanisms in general, and then, the parameter passing
mechanisms in Java
•
What constructors of a class are and how to use them
•
Initializers of a class
final
variables, classes, and methods
•
Declaring
•
How to declare and use varargs parameters
•
What generic classes are and how to use them
What Is a Class?
Classes are the basic units of programming in the object-oriented paradigm. In the chapter on writing java programs,
you looked at some elementary aspects of a class in Java, for example, using the
class
keyword to declare a class,
declaring the
main()
method to run a class, etc. This chapter explains how to declare and use a class in detail.
Let's start with a simple example of a class in the real world to build the technical concept of a class in Java. When
you look around, you see a number of objects, such as books, computers, keyboards, tables, chairs, humans, etc. Each
object that you see belongs to a class. Ask yourself a simple question, “Who am I?” Your obvious answer would be:
I am a human. What do you mean by saying that you are a human being? You mean that a human class exists in the
world and you are one of the instances (“being”) of that class. You also understand that other humans (other instances
of the human class) also exist, who are similar but not the same to you. Both you and your friend, being instances of
the same human class, have the same properties, such as name, gender, height, weight, and behaviors, such as the
ability to think, talk, walk, etc. However, the properties and behaviors differ for you and your friend in value, quality,
or both. For example, you both have a name and the ability to talk. However, your name may be Richard and your
friend's name may be Greg. You may talk slowly whereas your friend may talk fast. If you want to prepare a model for
you and your friend to examine your behaviors, there are two choices.