Line At A Time
Lesson 6: Putting It Together
Putting It Together A constructor, two fields and a method: a real class.
1class Dog {
2 String name;
3 int age;
4
5 Dog(String dogName, int dogAge) {
6 name = dogName;
7 age = dogAge;
8 }
9
10 void introduce() {
11 System.out.println("I am " + name + ", age " + age);
12 }
13}
14
15public static void main(String[] args) {
16 Dog rex = new Dog("Rex", 3);
17 Dog bella = new Dog("Bella", 5);
18 rex.introduce();
19 bella.introduce();
20}
Terminal
$ javac Main.java
$ java Main
I am Rex, age 3
I am Bella, age 5
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;
Second field: every Dog has an age too.
Dog(String dogName, int dogAge) {
A constructor can take several values, one for each field it needs to fill in.
name = dogName;
Stores the first value into the name field.
age = dogAge;
Stores the second value into the age field.
}
This } closes the constructor.
void introduce() {
A method every Dog can do: introduce itself.
System.out.println("I am " + name + ", age " + age);
Uses BOTH fields of whichever dog is introducing itself.
}
This } closes the method.
}
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", 3);
Builds rex with both values in one go.
Dog bella = new Dog("Bella", 5);
And a second, completely separate dog.
rex.introduce();
rex introduces himself...
bella.introduce();
...and bella introduces herself. Same method, different objects, different answers: that is the magic of classes.
}
This } closes the main method.