Search code examples
javaparametersconstructordefault

Constructors and how they are utilized


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?


Solution

  • 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.