Task 1 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 — where a class lives

Lesson

Your own class sits next to Main

So far every program was one class — Main — and everything happened inside main. Now you will write your own classes. A class you write goes in the same file, next to Main, as a separate block.

One rule about the file: only one class may be marked public, and that is Main. Your own classes are written without public in front.


Worked example

class Dog {              // your class — no public
    String name;         // a field
    int age;             // another field
}

public class Main {      // the one public class
    public static void main(String[] args) {
        Dog d = new Dog();          // make an object
        d.name = "Rex";             // fill its fields
        d.age = 3;
        System.out.println(d.name + " is " + d.age);
    }
}

The class is a blueprint: it lists what every Dog has. new Dog() builds one actual object from that blueprint, and d.name reaches into it.

This also answers an old question. main is static, which is why the methods you wrote in module 3 had to be static too. Methods that belong to an object — like the ones you will write in 4.3 — do not need it: they are called on the object, as d.bark().


▶ Try it: the whole file is here — your class and Main together. Run it, then add a second dog, or add a third field to the class.



Where is your own class written?


How many classes in one file may be public?


What does new Dog() do?


True or false?


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.name = "Rex";
        d.age = 3;
        System.out.println(d.name + " is " + d.age);
    }
}