Line At A Time
Lesson 5: Constructors
Constructors Fill in the fields at the moment an object is built.
1class Dog {
2 String name;
3
4 Dog(String dogName) {
5 name = dogName;
6 }
7}
8
9public static void main(String[] args) {
10 Dog rex = new Dog("Rex");
11 System.out.println(rex.name);
12}
Terminal
$ javac Main.java
$ java Main
Rex
Every line, explained
class Dog {
class Dog { ... } defines a class: a blueprint describing what every Dog has and can do. A blueprint on its own does nothing; it is a plan, waiting to be built from.
String name;
A variable declared inside a class is called a field. Every Dog built from this blueprint gets its OWN copy: its own little name box.
Dog(String dogName) {
This is a constructor: a special method that runs automatically when new Dog(...) is built. You can spot one because it has the SAME name as the class and no return type, not even void.
name = dogName;
Whatever the builder passes in (dogName) is stored into the new dog's name field. No more forgetting to set the name afterwards!
}
This } closes the constructor.
}
This } closes the class.
public static void main(String[] args) {
The main method: where the program starts, exactly as in Intro to Java.
Dog rex = new Dog("Rex");
Now new Dog("Rex") hands "Rex" straight to the constructor, so the object is born with its name already filled in.
System.out.println(rex.name);
System.out.println(...) prints to the terminal, exactly as in Intro to Java.
}
This } closes the main method.