Java Reference
In-Depth Information
instantiate, hundreds of students, each with their own properties. In object‐oriented programming
terms, you say that you want to create a student object that's an
instance
of the
class of objects
known as
Student
.
Objects are created using the
new
keyword. For example, to create a new student, you would simply
write the following statement:
new Student();
Of course, just creating a student in itself does not help you much, as you need to have a way to
access this particular object later on. How do you do so? By simply assigning the newly created stu-
dent to a variable, of course:
Student myFirstStudent = new Student();
Now you can use the
myFirstStudent
variable to access the first student later. You might be won-
dering why the parentheses appear at the end of student. It's not a method definition, right? So, why
not just write:
Student myFirstStudent = new Student; // Incorrect!
The reason is that when you instantiate a class, you are in fact actually calling a special method
of the class called a
constructor
. Since it is a method, it can take a number of arguments. For
example, you might have defined the class so that you immediately need to pass a name for the
new student:
Student myFirstStudent = new Student("Sophie", "Last Name");
In fact, this is a better way to define the class, as it doesn't make much sense to allow program-
mers to define students who do not have a name. Since you are just getting started with classes
and objects, however, you can be a bit sloppy in the name of learning. Don't worry, you will
return to
constructors
later in this chapter. For now, the classes can be instantiated without any
arguments.
Note
Observant readers might wonder why the
Student
class definition does
not contain a constructor method to create a new
Student
, even when this
method does not take any arguments. For all the other methods, you see that
you have written, for example:
int numberOfFriends() {
// Return the number of friends the student has.
return 0;
}
So where is the constructor method? The answer is that you do not have to
define it. When you do not supply any constructor method, Java will be smart
enough to know that it should just create a new
Student
object with all its vari-
ables set to the default values when you write:
Student myFirstStudent = new Student();
You will explore constructors in more detail later in this chapter.
Search WWH ::
Custom Search