Java – Constructor

Constructor: a special kind of method that is designed to initialize the instance variables for an object:

  • public ClassName(anyParameters){code}
  • A constructor must have the same name as the class
  • A constructor has no type returned, not even void
  • Constructors are typically overloaded

A constructor is called when an object of the class is created using new
ClassName objectName = new ClassName(anyArgs);

  • The name of the constructor and its parenthesized list of arguments (if any) must follow the new operator
  • This is the only valid way to invoke a constructor:  a constructor cannot be invoked like an ordinary method

If a constructor is invoked again (using new), the first object is discarded and an entirely new object is created

  • If you need to change the values of instance variables of the object, use mutator methods instead

If a constructor is not explicitly created, Java will automatically create a constructor for the class and assign default values to the instance variables based on the instance variable type

  • If you create 1 constructor a default constructor will not be created.  A default constructor will only be created if no constructors have been created