# 3.4 Writing Constructors

Each coding exercise has its own folder. Open its `.java` file and press **Run** to try it. **Run Tests** checks every graded exercise in this lesson at once.

In Unit 1, we learned how to create objects by calling **constructors**. To review, a call to a constructor consists of the word `new` followed by the name of the class being constructed, and then an argument list in parentheses. For example, here is how we create `World`, `Turtle`, and `Person` objects.

```java
// To create a new object, write:
// ClassName variableName = new ConstructorName(arguments);
World world = new World();
Turtle t = new Turtle(world);
Person p = new Person("Pat", "pat@gmail.com", "123-456-7890");
```

Now it’s time to learn to write our own constructors.

## Constructor Signature

In the source code for a class, constructors are usually written after the instance variables and before any methods.

The signature of a constructor is similar to the signature of a method except there is no return type, not even `void`, and instead of a method name, the name of the constructor is always the same as the name of the class. The constructors you write will be marked `public`. Like methods, constructors also have a **parameter list** specified in parenthesis that declare the variables that will be used to hold the arguments passed when the constructor is called.

```java
public class ClassName
{
    /* Instance variable declarations go here, before constructors */

    /* Constructor - same name as Class, no return type */
    public ClassName()
    {
        /* Implementation not shown */
    }

    /* Method definitions go here, after constructors */
}
```

> Constructors must have the same name as the class! Constructors have no return type!

## The Job of a Constructor

The job of a constructor is to set the initial values for the object’s instance variables to useful values. But what does “useful” mean? Sometimes we describe the values of all an object’s instance variables at a given time as the object’s **state**. And we say an object is in a **valid state** when all its instance variables have values that let us use the object by invoking its public methods. So another way to describe the job of a constructor is to set the object’s instance values so it’s in a valid state and ready to be used. Classes can have zero or more constructors but they should all produce an object in a valid state.

An object’s **state** refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. This defines a **has-a** relationship between the object and its instance variables. For example, a Person object **has** a name, email, and phone number attributes. A constructor is used to set the initial state of an object, which should include initial values for all instance variables. For example, `new Person("Pat", "pat@gmail.com", "123-456-7890")` calls the Person constructor with the values to fill in for its name (“Pat”), email (”[pat@gmail.com](mailto:pat@gmail.com)”), and phone number (“123-456-7890”). When a constructor is called, memory is allocated for the object and the associated object reference is returned. Constructor parameters, if specified, provide data to initialize instance variables.

The easiest way to write a constructor is to *not* write one. If you do not write a constructor your class will automatically get what is called the **default constructor** with no parameters. This constructor will initialize all your instance variables to the default value for their type:

> - 0 for `int`
> - 0.0 for `double`
> - `false` for `boolean`
> - `null` for all reference types

If those default values are sufficient to put your object into a valid state you may not need to write a constructor at all.

Usually, however, if you are writing a class that has instance variables, you need to initialize your instance values to some other values. In that case you probably need to write a constructor that takes arguments and uses them to initialize your instance variables.

For example, consider the constructor from the `Person` class from the last lesson.

```java
public Person(String initName, String initEmail, String initPhone)
{
    name = initName;
    email = initEmail;
    phoneNumber = initPhone;
}
```

This constructor ensures that all three of the instance variables (`name`, `email`, and `phoneNumber`) in `Person` are initialized to the values provided by whatever code called the constructor. For example, in the constructor call `new Person("Pat", "pat@gmail.com", "123-456-7890")`, the argument “Pat” is passed into the parameter variable `initName`, which the constructor then assigns to the instance variable `name`.

One important note: if you do write a constructor, Java will not generate the default constructor for you. This is a good thing because it lets you make sure that instances of your class are always properly initialized. With this constructor in place, for instance, there’s no way to construct a `Person` object without providing the three required `String` values.

Sometimes you will want to write more than one constructor so that there are different ways of making an instance of your class. One reason to do that is to make it convenient to create instances from different kinds of arguments. This is called **overloading**. You could write a no-argument constructor for `Person` that provides fill-in values like the following, if those make sense for your program. It’s up to you to decide if this is actually a useful value to have or if it would be better to force the users of the `Person` class to choose the values themselves using the constructor with arguments.

```java
public Person()
{
    name = "Anonymous";
    email = "unknown";
    phoneNumber = "unknown";
}
```

> Check your understanding: Click on all the lines of code that are part of constructors in the following class.
>
> ```java
> public class Name
> {
>     private String first;
>     private String last;
>
>     public Name(String theFirst, String theLast)
>     {
>         first = theFirst;
>         last = theLast;
>     }
>
>     public void setFirst(String theFirst)
>     {
>         first = theFirst;
>     }
>
>     public void setLast(String theLast)
>     {
>         last = theLast;
>     }
>
> }
> ```
>
> Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-3-4-constructors.html#name_constructor

> Check your understanding: What best describes the purpose of a class’s constructor? — answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-3-4-constructors.html#constructor-purpose

### Exercise 1

The following class defines a `Fraction` with the instance variables `numerator` and `denominator`. Complete the body of its 2 constructors. The no-argument constructor should set the default instance variable values to 1 rather than 0 since a fraction with 0 in the denominator is not valid. The constructor with parameters should copy those parameters into the instance variables. What will the code print out? Try tracing through it.

> Open the `01-class-Fraction` folder and edit `Fraction.java`. Press **Run** to try it; **Run Tests** checks it (5 tests).

### Exercise 2

The following class defines a Car with the instance variables model and year, for example a Honda 2010 car. However, some of the code is missing. First, fill in the code to create a `Car` constructor. Then, fill in the code to call the constructor in the main method to create 2 `Car` objects. The first car should be a 2023 Ford and the second car should be a 2010 Honda. Run your program and make sure it works and prints out the information for both cars.

> Open the `02-class-Car` folder and edit `Car.java`. Press **Run** to try it; **Run Tests** checks it (1 test).

## Coding Challenge: Student Class

We encourage you to work in pairs for this challenge to create a Student class with constructors.

1. First, brainstorm in pairs to do the **Object-Oriented Design** for a Student class. What data should we store about Students? Come up with at least 4 different instance variables. What are the data types for the instance variables?
2. Write a Student class below that has your 4 instance variables and write a constructor that has 4 parameters to set all of the instance variables.
3. Add a print() method that uses System.out.println to print out all the instance variables.
4. Add a main method that constructs at least 2 Student objects using the constructor with different values and then calls their print() methods.

### Exercise 3

Create a class Student with 4 instance variables, a constructor, and a print method. Write a main method that creates 2 Student objects with the constructor and calls their print() method.

> Open the `03-challenge-Student-class` folder and edit `Student.java`. Press **Run** to try it; **Run Tests** checks it (4 tests).

## Design a Class for your Community

In the last lesson, you came up with a class of your own choice relevant to you or your community. In this lesson, you will add a constructor to this class.

1. Consult your completed worksheet or your code in [lesson 3.3 Community Challenge](/lessons/CSA-3.3-Anatomy-of-a-Java-Class) for the class name and its 3 instance variables that you created. Copy them into the exercise below.
2. Add a constructor with 3 parameters to set all of the instance variables to the given parameters.
3. Write a print() method that uses `System.out.println` to print out all the instance variables.
4. Write a main method that constructs at least 2 objects of your class using the constructor and then calls their `print()` methods.

### Exercise 4

Copy your class with its 3 instance variables from [lesson 3.3 Community Challenge](/lessons/CSA-3.3-Anatomy-of-a-Java-Class). Add a constructor with 3 parameters to set all of the instance variables to the given parameters. Write a print() method that uses System.out.println to print out all the instance variables. Write a main method that constructs at least 2 objects of your class using the constructors and then calls their print() methods.

> Open the `04-community-challenge2` folder and edit `Main.java`. Press **Run** to try it; **Run Tests** checks it (4 tests). Name the class, then rename the file to match.

## Summary

- (AP 3.4.A.1) An object’s **state** refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. This defines a **has-a** relationship between the object and its instance variables.
- (AP 3.4.A.2) A constructor is used to set the initial state of an object, which should include initial values for all instance variables. When a constructor is called, memory is allocated for the object and the associated object reference is returned. Constructor parameters, if specified, provide data to initialize instance variables.
- A constructor must have the same name as the class! Constructors have no return type!
- (AP 3.4.A.4) When no constructor is written, Java provides a no-parameter constructor, and the instance variables are set to default values according to the data type of the attribute. This constructor is called the **default constructor**. (Note that AP 3.4.A.3 is covered in lesson 3.6).
- (3.4.A.5) Default values used by the default constructor:
  > - The default value for an attribute of type `int` is `0`.
  > - The default value of an attribute of type `double` is `0.0`.
  > - The default value of an attribute of type `boolean` is `false`.
  > - The default value of a reference type is `null`.

## AP Practice

> Check your understanding: Consider the definition of the Cat class below. The class uses the instance variable isSenior to indicate whether a cat is old enough to be considered a senior cat or not.
>
> ```java
> public class Cat
> {
>     private String name;
>     private int age;
>     private boolean isSenior;
>
>     public Cat(String n, int a)
>     {
>         name = n;
>         age = a;
>         if (age >= 10)
>         {
>             isSenior = true;
>         }
>         else
>         {
>             isSenior = false;
>         }
>     }
> }
> ```
>
> Which of the following statements will create a Cat object that represents a cat that is considered a senior cat?
>
> Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-3-4-constructors.html#AP-constructor1

> Check your understanding: Consider the following class definition. Each object of the class Cat will store the cat’s name as name, the cat’s age as age, and the number of kittens the cat has as kittens. Which of the following code segments, found in a class other than Cat, can be used to create a cat that is 5 years old with no kittens?
>
> ```java
> public class Cat
> {
>     private String name;
>     private int age;
>     private int kittens;
>
>     public Cat(String n, int a, int k)
>     {
>         name = n;
>         age = a;
>         kittens = k;
>     }
>     public Cat(String n, int a)
>     {
>         name = n;
>         age = a;
>         kittens = 0;
>     }
>     /* Other methods not shown */
> }
>
> I.   Cat c = new Cat("Sprinkles", 5, 0);
> II.  Cat c = new Cat("Lucy", 0, 5);
> III. Cat c = new Cat("Luna", 5);
> ```
>
> Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-3-4-constructors.html#AP-constructor2

> Check your understanding: Consider the following class definition.
>
> ```java
> public class Cat
> {
>     private String color;
>     private boolean isHungry;
>     /* missing constructor */
> }
> ```
>
> The following statement appears in a method in a class other than Cat. It is intended to create a new Cat object c with its attributes set to “black” and true. Which of the following can be used to replace **missing constructor code** in the class definition so that the object c below is correctly created?
>
> ```java
> Cat c = new Cat("black", true);
> ```
>
> Answer it on CS Awesome: https://runestone.academy/ns/books/published/csawesome2/topic-3-4-constructors.html#AP-constructor3
