Coding for All
Lesson 1: What Is a Class?
What Is a Class? Write a blueprint and build an object from it.
1class Dog {
2 String name;
3}
4
5public static void main(String[] args) {
6 Dog rex = new Dog();
7 rex.name = "Rex";
8 System.out.println(rex.name);
9}
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. Note there is no value yet: the blueprint only says every Dog will HAVE a name.
}
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". This stores "Rex" in this particular dog's name field.
System.out.println(rex.name);
System.out.println(...) prints to the terminal, exactly as in Intro to Java. It prints what is inside rex's name field.
}
This } closes the main method.