Constructors: The Method
Constructors: The Method
A Java program can be as small as a single class, but usually a single program will be made up of tens or
even hundreds of classes!
A good Java program is one that divides the logic appropriately so that each class ends up containing
everything related to that class, and nothing more!
Classes would be calling each other's methods and updating their fields to make up the logic of the
entire program all together!
BUT, where should the program start from exactly? In other words, if a method can call another method
and that method can call another, which method will start this sequence the very first time?
public : Means you can run this method from anywhere in your Java program (we will talk
more about public and private methods later
static : Means it doesn't need an object to run, which is why the computer starts with this
method before even creating any objects (we will also talk more about static methods later on)
void : Means the main method doesn't return anything, it just runs when the program starts,
and once it's done the program terminates
main : Is the name of the method
String [] args : Is the input parameter (array of strings) which we will cover how to use it
later in this lesson as well!
This main method is the starting point for any Java program, when a computer runs a Java program,
it looks for that main method and runs it.
Inside it you can create objects and call methods to run other parts of your code. And then when the
main method ends the program terminates.
If this main method doesn't exist, or if there's more than one, the Java program won't be able to run
at all!
The main method can belong to any class, or you can create a specific class just for that main
method which is what most people do.
Constructors
Constructors are special types of methods that are responsible for creating and initializing an object
of that class.
Creating a constructor
Creating a constructor is very much like creating a method, except that:
Default constructor
A Default constructor is one that doesn't take any input parameters at all!
It's optional, which means if you don't create a default constructor, Java will automatically assume
there's one by default that doesn't really do anything.
However, if the class has fields that need to be initialized before the object can be used, then you
should create one that does so.
For example, assume we have a class Game that has an integer member field score , we'd like to
make sure that any object of type Game will start with the score value set to 0 . To do so, we need to
create a default constructor that will initialize the mScore field
class Game{
int mScore;
// Default constructor
Game(){
// Initialize the score here
mScore = 0;
}
}
Parameterized constructor
As we've mentioned earlier, a constructor can also take input parameters.
Let's assume that some games start with a positive score value and not just 0 , that means we need
another constructor that takes an integer parameter as an input, and uses that to initialize the score
variable.
class Game{
int score;
// Default constructor
Game(){
score = 0;
}
// Constructor by starting score value
Game(int startingScore){
score = startingScore;
}
}
Accessing a constructor
Unlike normal methods, constructors cannot be called using the dot . modifier, instead, every time
you create an object variable of a class type the appropriate constructor is called. Let's see how:
The new keyword
To create an object of a certain class, you will need to use the new keyword followed by the
constructor you want to use, for example:
Game tetris = new Game();
This will create an object called tetris using the default constructor (i.e. tetris will have an initial
score value of 0)
To create a game that is initialized with a different starting score you can use the second
constructor:
However, this privilege goes away once you create any constructor of your own! Which means if you
create a parameterized constructor and want to also have a default constructor, you will have to
create that default constructor yourself as well.
Self Reference
Sometimes you'll need to refer to an object within one of its methods or constructors, to do so you
can use the keyword this .
this is a reference to the current object — the object whose method or constructor is being called.
You can refer to any field of the current object from within a method or a constructor by using this .
Using this with a Field
The most common reason for using the this keyword is because a field has the same name as a
parameter in the method or constructor
For example, if a Position class was written like this
class Position {
int row = 0;
int column = 0;
//constructor
Position(int r, int c) {
row = r;
column = c;
}
}
A more readable way would be to use the same names ( row & column ) for the constructor
parameters which means you will have to use the this keyword to seperate between the fields and
the paramters:
class Position {
int row = 0;
int column = 0;
//constructor
Position(int row, int column) {
this.row = row;
this.column = column;
}
}
In the second snippet, the constructor Position accepts the parameters row and column , but the
class Position also includes two fields with the exact same name.
Using this.row compared to row means that we are referring to the field named row rather than
the input parameter.
There are plenty more uses for the keyword this that you can check out here, but they are slightly
outside the scope of this course.
The Contacts Manager
Assume you're writing a Java program that's responsible for storing and managing all your
friends' contact information.
We'll start by creating a class that's responsible for storing all contact information of a single
person, it will look something like this:
class Contact{
String name;
String email;
String phoneNumber;
}
All fields, no methods, since a contact object itself won't be "doing" much actions itself in the
scope of this program, it's merely a slightly more advanced data type that can store a few strings
in 1 variable.
Note: Noticed how we used a String to store the phone number instead of using int ! Can you
think of a reason why?
Yes, integers are just numbers, which means 01 and 001 and 1 will all be considered exactly the
same when stored as integers, but will be considered different when stored as Strings.
Also the largest value for an integer is 2,147,483,647, so a 10 digit number that starts with a 9 for
example cannot be stored in a single integer.
The ContactsManager class methods
The first method we will create in the ContactsManager class is the addContact method which will
add a Contact object to the Contact array myFriends :
void addContact(Contact contact){
myFriends[friendsCount] = contact;
friendsCount++;
}
The method addContact takes a Contact object as an input parameter, and uses
the friendsCount value to fill that slot in the array with the contact that was passed into the method.
Then, since we need to move that counter to point to the following slot in the array, we
increment friendsCount using the increment operation ++
Now, let's add another method called searchContact that will search through the array using a
name String and return a Contact object once a match is found:
Contact searchContact(String searchName){
for(int i=0; i<friendsCount; i++){
if(myFriends[i].name.equals(searchName)){
return myFriends[i];
}
}
return null;
}
This method loops over the array, and for each element myFriends[i] it compares the name field to
the searchName value using this if statment:
if(myFriends[i].name.equals(searchName))
This if statement will evaluate to true if the searchName is equal to the name field in the Contact
stored in myFriends[i]
If it was a match, the loop will return the matching Contact object myFriends[i] . Otherwise. it will
return null indicating that it could not find that contact.
Putting all this together, our ContactsManager class will look like this:
class ContactsManager {
// Fields:
Contact [] myFriends;
int friendsCount;
// Constructor:
ContactsManager(){
friendsCount = 0;
myFriends = new Contact[500];
}
// Methods:
void addContact(Contact contact){
myFriends[friendsCount] = contact;
friendsCount++;
}
Later on in this course, we will see how to read input from the user to make this program more
powerful.
NEXT