To actually make an object from a class, use new: new Dog() builds a fresh Dog. Store it in a variable whose type is the class name. Every new makes a separate object with its own fields.
new
new Dog()
Dog
Dog a = new Dog(); // one dog Dog b = new Dog(); // a different dog a.name = "Rex"; b.name = "Fido"; // does not affect a
a and b are two independent objects.
a
b
▶ Try it: run this — two separate Dog objects, each with its own name. Change the names and re-run.
name
What does new Dog() do?
How many objects does this create?
Dog a = new Dog(); Dog b = new Dog();
Assemble a statement that builds a Dog and stores it in d.
d
True or false?
Type exactly what this program prints.
class Cat { String name; } public class Main { public static void main(String[] args) { Cat a = new Cat(); a.name = "Tom"; Cat b = new Cat(); b.name = "Kit"; System.out.println(a.name); System.out.println(b.name); } }