Java Reference
In-Depth Information
Have you noticed throughout the topic so far that parentheses appear when
using the new keyword to instantiate an object? For example, a new Radio
object is instantiated as follows:
Radio r = new Radio();
I have not explained those empty parentheses, but I am ready to now. Any
time you see parentheses, it looks as if a method is being invoked. This is
exactly what is happening when you use the new keyword, except that a
method is not invoked. One of the constructors in the class is invoked.
In fact, the only time you can invoke a constructor is when the object is being
instantiated. Constructors are similar to methods, but keep in mind that they
are not methods. They behave quite differently, as you will see in Chapter 6,
“Understanding Inheritance.”
Classroom Q & A
Q: Wait a minute. We haven't added a constructor to any of the classes
we have seen up until now. Do you have to add a constructor to
every class?
A: You are right. We must not have to add a constructor because our
classes seem to be fine without one, so the answer to your ques-
tion is no. If you do not add a constructor to your class, the com-
piler writes one for you. This “free” constructor is known as the
default constructor .
Q: How does the compiler know what I want my default constructor
to do?
A: The compiler doesn't know. The default constructor that you get
for free has an empty parameter list and doesn't do anything.
Q: Then why bother? It seems like a waste of code to have a con-
structor that doesn't do anything.
A: Because every class must have a constructor. When you instantiate
a class, the new operator must invoke a constructor. The fact that
the compiler adds a default constructor to your class is purely for
convenience. In almost all development situations you find your-
self in, you will add at least one constructor yourself to all of your
classes. Before we write our own constructors, though, let's take a
quick look at this default constructor.
Search WWH ::




Custom Search