java · level 2 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A fills in a new object as it is built.
Remember building new Pet() and then filling in each field, one line at a time? Forget a line, and that field stays empty. A constructor fixes . It runs while new builds the object, so every pet starts complete.
A constructor looks like a method with the class's name and no return type: Pet(String name, int age). Inside, this.name = name; copies the parameter into the field. this means the object being built, so this.name is its field.
Now new Pet("Rex", 3) builds and fills in one go. Leave out an argument, and Java refuses to compile.
public class Main {
static class Pet {
String name;
int age;
Pet(String name, int age) {
this.name = name;
this.age = age;
}
}
public static void main(String[] args) {
Pet rex = new Pet("Rex", 3);
Pet tiddles = new Pet("Tiddles", 5);
System.out.println(rex.name + " is " + rex.age);
System.out.println(tiddles.name + " is " + tiddles.age);
}
} Once a class has a constructor with parameters, plain new Pet() no longer works.
guess first
Someone forgot this. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static class Book {
String title;
Book(String title) {
title = title;
}
}
public static void main(String[] args) {
Book book = new Book("Matilda");
System.out.println(book.title);
}
}
your turn
Your turn. Build two films.
Fill in the constructor on lines 6 and 7 using this. Then make a second film of your choice on line 12, and press run.
output
press run to see what happens
fix it
The new bike is missing a detail. Fix it!
output
press run to see what happens
- Java says the constructor
cannot be applied to given typeson line 11. Count the arguments. - The constructor on line 5 asks for a colour and a number of gears. Line 11 only hands over a colour.
- Change line 11 to
Bike bike = new Bike("red", 21);, then press run.
nailed it
your objects arrive ready to use. :D
- A constructor runs when
newbuilds an object. - It has the class's name and no return type.
this.name = name;copies a parameter into a field.
new words in your collection
- constructor
- this
This lesson isn’t saved. A free account remembers every lesson you finish.