Constructor Methods Flashcards
1) The Constructor Method
A constructor in Java is a special method that is used to i_______ objects. The constructor is called when an object of a class is created.
Initialize
2) When is a constructor method called?
When an object of a class is created.
3)
Note that the constructor name must match the c______ name, and it cannot have a return type (like void).
Here is an example of a constructor method for a class called Dog.
e.g. public Dog( ) {
}
class
4)
All classes have constructors by d_______: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
default
5)
C________ do not have to have any code inside of them, but they can if we want them to.
Let’s say that every time you want to create an instance of a dog, you want to give them 4 legs by default. You could add some code like this:
public Dog( ) {
this.numberOfLegs = 4
}
constructors
6) Constructors with Parameters
Constructors can also take parameters, which is used to i_________ attributes.
The following example adds an int y parameter to the constructor.
public Main(int y) {
x = y;
}
intialize
7) Can we have more than one constructor in a class?
Yes
There can be multiple constructors in a class. However, the parameter list of the constructors should not be the same.
This is known as constructor overloading.