Task 4 of 10 · 0 solved · 10 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

4.1 Objects and fields — creating an object with new

Lesson

Building an object

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.


Worked example

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.


▶ Try it: run this — two separate Dog objects, each with its own name. Change the names and re-run.



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.


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);
    }
}