Two Dogs
Build two objects from one blueprint.
1class Dog {
2 String name;
3}
4
5public static void main(String[] args) {
6 Dog rex = new Dog();
7 Dog bella = new Dog();
8 rex.name = "Rex";
9 bella.name = "Bella";
10 System.out.println(rex.name);
11 System.out.println(bella.name);
12}
$ javac Main.java
$ java Main
Rex
Bella
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.
}- 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. First object.
Dog bella = new Dog();- A second new Dog() builds a completely separate object: one blueprint, as many objects as you like, like one house plan and a whole street of houses.
rex.name = "Rex";- The dot reaches inside an object: rex.name means "the name field of the object stored in rex".
bella.name = "Bella";- Each object has its OWN name field; changing bella's name does not touch rex's.
System.out.println(rex.name);- System.out.println(...) prints to the terminal, exactly as in Intro to Java.
System.out.println(bella.name);- System.out.println(...) prints to the terminal, exactly as in Intro to Java. Two objects, two different names.
}- This } closes the main method.