Reputation: 63
I'm reading through my programming text and I have what I feel is a pretty logical question concerning constructors.
For example if I have the code:
public class Ship{
String name;
int position;
public Ship(int position){
this.position = position;
}
public Ship(String name){
this.name = name;
}
public Ship(){
name = "Titanic";
position = 0;
}
}
So if I have my jargon correct the Ship()
is the default constructor. Whereas the constructors with parameters are the initialization constructors.
Now that is the background...here is my question! When I used one of the constructors that contain an argument, what happens to the field that is being utilized ( in this example the other field ). For example when I call Ship(5)
what is the value of the name
data field? Does it adopt the value of the default, or just the default for the data type?
Does this mean I have to set a value for the other field if I call this single argument constructor?
Upvotes: 0
Views: 282
Reputation: 16987
The field gets the default field value: 0 for numbers, null for objects. You will have to set the value of the other field in the one-argument constructor if the default is not what you want.
Upvotes: 3
Reputation: 178263
Any instance variables that you don't initialize are given default values by Java. Primitive types get the value 0
, and reference types are null
.
You don't have to initialize the values, but for clarity, it's best to explicitly initialize all values.
Upvotes: 5