Java Reference
In-Depth Information
tv1's channel is 30 and volume level is 3
tv2's channel is 3 and volume level is 2
The program creates two objects in lines 3 and 8 and invokes the methods on the objects to
perform actions for setting channels and volume levels and for increasing channels and vol-
umes. The program displays the state of the objects in lines 14-17. The methods are invoked
using syntax such as
tv1.turnOn()
(line 4). The data fields are accessed using syntax such
as
tv1.channel
(line 14).
These examples have given you a glimpse of classes and objects. You may have many
questions regarding constructors, objects, reference variables, accessing data fields, and
invoking object's methods. The sections that follow discuss these issues in detail.
9.1
✓
✓
Describe the relationship between an object and its defining class.
Check
9.2
How do you define a class?
Point
9.3
How do you declare an object's reference variable?
9.4
How do you create an object?
A constructor is invoked to create an object using the
new
operator.
Key
Point
Constructors are a special kind of method. They have three peculiarities:
A constructor must have the same name as the class itself.
constructor's name
■
Constructors do not have a return type—not even
void
.
■
no return type
Constructors are invoked using the
new
operator when an object is created.
Constructors play the role of initializing objects.
■
new
operator
The constructor has exactly the same name as its defining class. Like regular methods,
constructors can be overloaded (i.e., multiple constructors can have the same name but differ-
ent signatures), making it easy to construct objects with different initial data values.
It is a common mistake to put the
void
keyword in front of a constructor. For example,
overloaded constructors
public void
Circle() {
}
no
void
In this case,
Circle()
is a method, not a constructor.
Constructors are used to construct objects. To construct an object from a class, invoke a
constructor of the class using the
new
operator, as follows:
constructing objects
new
ClassName(arguments);
For example,
new Circle()
creates an object of the
Circle
class using the first construc-
tor defined in the
Circle
class, and
new Circle(25)
creates an object using the second
constructor defined in the
Circle
class.
A class normally provides a constructor without arguments (e.g.,
Circle()
). Such a con-
structor is referred to as a
no-arg
or
no-argument constructor
.
A class may be defined without constructors. In this case, a public no-arg constructor with
an empty body is implicitly defined in the class. This constructor, called a
default constructor
,
is provided automatically
only if no constructors are explicitly defined in the class
.
no-arg constructor
default constructor
✓
✓
Check
9.5
What are the differences between constructors and methods?
Point
9.6
When will a class have a default constructor?
Search WWH ::
Custom Search