Task 6 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 — reading and writing fields

Lesson

Using an object's fields

Reach a field through the object with a dot: object.field. You can read it (use its value) or write it (assign a new value). Each object keeps its own field values, separate from every other object.


Worked example

Dog d = new Dog();
d.age = 3;                       // write
System.out.println(d.age);       // read -> 3
d.age = d.age + 1;               // read, then write -> 4
System.out.println(d.age);       // 4

▶ Try it: run this to set, read, and change a field. Change the numbers and re-run.



How do you read the name field of an object d?


Type exactly what this program prints.

class Dog {
    String name;
    int age;
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.age = 5;
        d.age = d.age + 2;
        System.out.println(d.age);
    }
}

Match each statement to what it does with a field.


True or false?