Skip to content
wannacode

Constructors and this

Problem

A €0 coffee

You create a product, just like in the last lesson, and fill in the fields line by line. You forgot one line:

Product coffee = new Product();
coffee.name = "Coffee";
coffee.quantity = 2;
System.out.println(coffee.name + ": €" + coffee.price * coffee.quantity);
Output
Coffee: €0.0

The coffee costs €0. The compiler does not complain: as far as it can tell, the price has a value, 0. The more fields a class has, the easier it is to miss one. And a product without a price should not be able to exist at all.

The idea

Constructor: no object without this data

A class can say what it needs before you can create an object from it. That is what the constructor is for: a special method that runs on new.

Main.java
class Product {
public String name;
public double price;
public int quantity;
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
}
public class Main {
public static void main(String[] args) {
Product coffee = new Product("Coffee", 7.50, 2);
System.out.println(coffee.name + ": €" + coffee.price * coffee.quantity);
}
}
Output
Coffee: €15.0
  • The constructor has exactly the same name as the class: Product.
  • It has no return type, not even void.
  • Its parameters are the data a product cannot do without. You pass them in the parentheses of new: new Product("Coffee", 7.50, 2).

Now there is no way to forget the price. If you pass two arguments instead of three, the program does not compile.

public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
Product coffee = new Product("Coffee", 7.50, 2);
System.out.println(coffee.name + ": €" + coffee.price * coffee.quantity);
Step by step, in words
  1. new sets aside a new object. Its fields hold default values.
  2. The constructor runs. The arguments are copied into its parameters.
  3. this.name = name: from the parameter into the field of this object.
  4. The same for the price and the quantity.
  5. The constructor is done and the parameters disappear. coffee gets an arrow to the finished object.
  6. The object comes out of new already filled in, so the price is not 0.

The idea

this: the field of this object

Inside the constructor there are two things called name: the parameter and the field. The bare name is the parameter, because it is "closer". For the field, you write this.name.

public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}

this is the object being created right now. this.name = name; means "store the name parameter in the name field of this object".

The parameters could have other names (productName), and then you would not need this. But matching names are common in Java, because you can see at once which parameter goes into which field.

Try it

Find the bug

The program should print "Tea: €3.2". The price shows up, but the name does not. Which line has the bug?

Pick the line with the bug.

The idea

What about new Product() from the last lesson?

In the last lesson there was no constructor, and new Product() worked. If you do not write a constructor, the compiler adds an empty one with no parameters. It is called the default constructor, and it leaves the fields with their default values.

As soon as you write your own constructor, the empty one is gone:

Product empty = new Product();
Compile error
error: constructor Product in class Product cannot be applied to given types;

That is the point: a product without a name and price can no longer be created. If you still need an empty constructor, write it yourself.

The idea

Several constructors

Most products in the cart come one at a time. Typing 1 every time gets tedious.

You can give the class a second constructor, without the quantity. It sits next to the first one:

public Product(String name, double price) {
this.name = name;
this.price = price;
this.quantity = 1;
}

This is the overloading from the "Methods" module: one name, different parameters. On new, the compiler picks the constructor based on the arguments.

More precisely, if you are curious

The two constructors repeat the same lines. Instead, the shorter one can call the longer one:

public Product(String name, double price) {
this(name, price, 1);
}

this(...) calls another constructor of the same class. It has to be the first line in the constructor.

This way, if you add a price check tomorrow, you write it in only one constructor.

Try it

Which constructor?

What will the program print?

class Product {
public String name;
public double price;
public int quantity;
public Product(String name, double price) {
this.name = name;
this.price = price;
this.quantity = 1;
}
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
}
Product bread = new Product("Bread", 1.20);
Product milk = new Product("Milk", 2.10, 3);
System.out.println(bread.quantity + " " + milk.quantity);
Answer

Try it

What is the constructor called?

What goes in the blank?

class Book {
    public String title;
    public String author;

    public (String title, String author) {
        this.title = title;
        this.author = author;
    }
}

Exercise

Objects created whole

Solve these in your editor. Every class gets a constructor with parameters for all of its fields.

1. Person. A Person class with a name and an age. Create two people and print their details.

Output
Maria, 34 years
Peter, 19 years

2. Animal. An Animal class with a species and an age. Create a 3-year-old cat and a 7-year-old dog.

Output
Species: cat, age: 3
Species: dog, age: 7

3. Dance move. A DanceMove class with a name and a duration in seconds. In the "Behavior" lesson, the move will learn to "perform" itself.

Output
moonwalk: 5 sec.

More practice

  • A book with a constructor. Rewrite Book from the last lesson with a Book(title, author) constructor. How many lines did you save in main?
  • A product with two constructors. Product with two constructors, as in the lesson. Make an array { new Product("Bread", 1.20, 2), new Product("Coffee", 7.50) } and print the name and quantity of each: "Bread x2", "Coffee x1". Then make the shorter constructor call the longer one.
  • Booking. A Booking class with the guest's name, the number of nights, and the price per night. Print what the stay costs: for 3 nights at €85, that is €255.

Test

Check yourself

1. When does the constructor run?
2. What return type goes before the constructor name?
3. The class has only a Product(name, price) constructor. What happens with new Product()?
4. The constructor says this.name = name; What is this.name?
5. The class has two constructors: one with a name and price, and one with a name, price and quantity. What is this called?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·