Loading...

Java Constructors

Write a class Box in Box.java with an int field size and a constructor Box(int n) that sets size = n;. In Hall.java, build one box with Box b = new Box(4);, then print b.size. Compile both files and run java Hall. The screen should show one line: 4. The number you pass to new reaches the constructor, and the constructor stores it on the object before main continues. Setting the field at build time — inside the constructor — is what this page teaches.

A method that runs when new builds

A constructor has the same name as the class. It has no void return type and no other return type. When main writes new Box(4), Java builds the object and runs that constructor with 4 as n. After the constructor finishes, the variable holds the ready object. That is the whole job of this page: pass a value into new, let the constructor store it on the field, then print the field so you can see the store worked.
Create Box.java first. The public class line is public class Box. Do not leave an older Cup or Chip class name here. Inside the braces declare int size;. Then write the constructor: Box(int n) { size = n; }. Use a parameter name different from size on this page so the assignment is clear without the word this. There is no main in Box.java. Save before you compile.
The field line alone does not put 4 into the object. The constructor body does that work when new calls it. If you skip the constructor and only declare the field, a later new Box(4) will not match, and javac will complain about the call. Keep both pieces in Box.java: the field and the constructor that writes into it.

Box with constructor

java
public class Box {
    int size;

    Box(int n) {
        size = n;
    }
}

Hall passes 4 into new Box

Create Hall.java in the same folder. Its public class line is public class Hall. Inside main, write Box b = new Box(4); then System.out.println(b.size);. The argument 4 goes into the constructor parameter n. You do not need a separate b.size = 4; line on this page — the constructor already stored the value. The print line is there so you can trust what the constructor did without guessing.
Keep Hall as the class that holds main. Do not put main inside Box for this lesson. The two-file shape matches the earlier objects and fields pages: one file defines the type, the other file builds and uses it. If you rename the file but leave an old public class Shelf line, javac will refuse until the names match again.

Hall builds one box

java
public class Hall {
    public static void main(String[] args) {
        Box b = new Box(4);
        System.out.println(b.size);
    }
}

From the folder that holds both files, run javac Box.java Hall.java. You can compile Box.java first and Hall.java second when both are complete. When parentheses, braces, and semicolons match, javac writes no line of its own. Then run java Hall — not java Hall.java, and not java Box. Leave the .java ending off the run command. Start the class that holds main. The same commands work on Windows and on macOS.
The program should print one line and stop: 4. It should not ask you to type. If the terminal waits for keyboard input, a nextLine call from an older exercise is still in a file. Delete that call and keep new Box(4) plus the print in Hall, with the constructor in Box. A waiting cursor is not a constructor problem; it is leftover input code sitting in the wrong place.
Walk the run once. Java starts at Hall.main. The expression new Box(4) builds a Box and calls Box(int n) with n equal to 4. The body writes size = n, so that object’s size becomes 4. Then main prints b.size and the screen shows 4. Nothing else should print. If you see ok or 3 or a Cup leftover, you are not running the Hall program from this page.
If you write new Box() with no argument while the only constructor needs an int, javac refuses. Match the call to the constructor’s parameter list. If you add void before the constructor name, it becomes an ordinary method, not a constructor, and new Box(4) will not run that body the way this page expects. The header must look like Box(int n), not void Box(int n), and not static int Box(int n).

Compared with assigning after new

On the fields page you wrote c.fill = 3; after new Cup(). That still works. This page moves the store into the constructor so the value is set while the object is built. A leftover Cup demo with c.fill = 3; is a different lesson. For this page keep Box and Hall and new Box(4). If Hall still has c.fill = 3; and this folder has no Cup class, remove that line. The compiler will not invent a Cup for you.
Printing b alone with System.out.println(b); does not show a clean 4. Print b.size to see the stored number. The object reference alone is not the field value. You already learned that pattern on the fields page; keep it here when you check the constructor’s work.
You can still assign a field after new in other programs. This lesson simply chooses the constructor path so the first useful value arrives at build time. Do not mix both styles in the same Hall demo on this page. One clear path is enough: argument to new, store in the constructor, print the field.

Two boxes, two sizes

Each new Box(...) runs the constructor again for a separate object. You can write Box a = new Box(2); and Box b = new Box(9);, then print both size fields. The first call stores 2 on one object. The second call stores 9 on another object. The two objects do not share one size slot.

Hall builds two boxes

java
public class Hall {
    public static void main(String[] args) {
        Box a = new Box(2);
        Box b = new Box(9);
        System.out.println(a.size);
        System.out.println(b.size);
    }
}

Compile and run again: javac Box.java Hall.java, then java Hall. The screen should show 2 on one line and 9 on the next. Each constructor call stored its own argument on its own object. Writing Box b = a; would not build a second object — use two new Box(...) calls when you want two sizes. Copying a reference is not the same as calling the constructor twice.
If both lines show the same number, check that each new passes a different argument and that you print a.size and b.size in that order. If javac stops on the second new, look for a missing parenthesis or a wrong class name left from an older file. Small typos in the second call are common when you paste the first line and forget to change the argument.

What this leaves for this

This page uses size = n; with different names. A later page — this — shows how to talk about the object’s own field when names collide. Stay with the clear parameter name n here. Do not invent this.size on this page unless you already know it; the lesson goal is the constructor call from new. The word this is the next topic, not a requirement for storing n into size today.
If javac cannot find Box while compiling Hall.java, check that Box.java sits in the same folder and that the class line is public class Box. If the screen shows 0, the constructor may be missing the assignment, or main may still use a no-arg shape that never sets size — keep Box(int n) { size = n; } and new Box(4). A zero on the screen usually means the field stayed at its default because the store never ran.
When the folder still holds Cup.java or Shelf.java from the fields page, leave them alone or delete them only if they confuse your compile command. Do not compile an old Shelf that still assigns c.fill and expect this page’s screen. Run java Hall after you compile the Box and Hall pair from this lesson.

Before this

You can declare int size;, write Box(int n) { size = n; }, and build with Box b = new Box(4); from Hall. Compile both files and run java Hall. The screen shows 4. The constructor runs when new builds the object. You passed the number at build time, the constructor stored it on the field, and the print proved the store. The next page is this, where you learn another way to name the object’s own fields inside its methods and constructors.
Keep the constructor header without void. Keep the argument on new. Keep the print on b.size. Those three habits are the checkpoint for this page before you move on.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top