Tino Intro To Java

Last modified: January 07, 2024

Constructors

Constructors are specialized methods that initialize an object. This is typically the place to initialize your instance variables and execute any code needed before the object is used. There are two kinds of constructors.

  1. Default constructor: A constructor with no parameters that initializes an object to default values.

  2. Parameterized constructors: Constructors with parameters that initialize an object according to the values passed in through the parameter list.

Example

Let's add both kinds to our Person class.

public class Person {

    // Instance Variables - fields storing info about the state
    //                      of an object (attributes/properties)
    ...

    // Constructors - Specialized methods that set an object up
    //                and initialize instance variables

    // Default constructor - no parameters ()
    public Person() {
        myAge = 17;
        myHeight = 1.53;
        isStudent = false;
        myName = "Frances";
    }

    // parameterized constructor - with parameters (a, b, c, ...)
    public Person(int age, double height, boolean student, String name) {
        myAge = age;
        myHeight = height;
        isStudent = student;
        myName = name;
    }

    // Remaining code not shown

}

A few things to notice:

  1. Constructors have the same name as the class name
  2. A class can have multiple constructors, which of course will have the same name, but must have different parameter types.
  3. A default constructor has no parameters inside the ()
  4. Both constructors initialize the attributes to initial values
  5. The additional constructor has a parameter list
  6. The additional constructor initializes the attributes to the parameter values
  7. A parameter list follows the format (data_type var_name1, data_type var_name2, ...)

Dark Mode

Outline