Line At A Time
Lesson 3: More Fields
More Fields Give the blueprint several fields.
1class Dog {
2 String name;
3 int age;
4}
5
6public static void main(String[] args) {
7 Dog rex = new Dog();
8 rex.name = "Rex";
9 rex.age = 3;
10 System.out.println(rex.name + " is " + rex.age);
11}
Terminal
$ javac Main.java
$ java Main
Rex is 3
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.
int age;
A class can have as many fields as you need, of any types. Every Dog now has a name AND an age.
}
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();
new Dog() builds a real object from the blueprint. The blueprint is the plan; the object is an actual dog. We store it in a variable of type Dog.
rex.name = "Rex";
The dot reaches inside an object: rex.name means "the name field of the object stored in rex".
rex.age = 3;
Same dot, different field: this fills in rex's age.
System.out.println(rex.name + " is " + rex.age);
System.out.println(...) prints to the terminal, exactly as in Intro to Java. + glues the pieces into one message, turning the number into text along the way.
}
This } closes the main method.