Item 25: Limit source files to a single top-level class

25.1 Limit to one top-level class per file

It is possible to define multiple top-level classes in one file, but there are no benefits and risks.

The problem with defining multiple top-level classes in one file

The risk is that one class definition is multiple. Which of the multiple definitions is used is affected by the order in which the source files are passed to the compiler. Consider the Main class, which references two top-level classes, such as:

public class Main {
    public static void main(String[] args) {
        System.out.println(Utensil.NAME + Dessert.NAME);
    }
}

Create Utensil class and Desert class in one file called Utensil.java.

class Utensil {
    static final String NAME = "pan";
}

class Dessert {
    static final String NAME = "cake";
}

At this time, if you execute Main, the message "pancake" will appear.

Here, suppose that the following class is defined in Dessert.java.

class Utensil {
    static final String NAME = "pot";
}

class Dessert {
    static final String NAME = "pie";
}

Now, if you compile with the command javac Main.java Dessert.java, it will fail and tell you that the Utensil and Dessert classes are duplicated. At this time, the compiler goes to Main.java first, and when it sees a reference to Utensil, it goes to Utensil.java and finds Utensil and the Dessert class. When the compiler goes to Dessert.java, it finds the Utensil and Dessert definitions again. If javac Main.java or javac Main.java Utensil.java is used, the result will be the same as before writing Desert.java (pancake display). However, when javac Dessert.java Main.java is used, it is displayed as potpie.

In this way, the behavior of the program will be affected by the order in which it is compiled.

Solution

The solution is simply to define only one top-level class in a source file.

Alternatively, define it as a static member class (Item24). If that class plays an auxiliary role to one other class, making it a static member class can improve readability and prevent unnecessary access (private static member class). To). The following is a specific example.

public class TestStaticMember {

    public static void main(String[] args) {
        System.out.println(Utensil.NAME + Dessert.NAME);
    }

    private static class Utensil {
        static final String NAME = "pan";
    }

    private static class Dessert {
        static final String NAME = "cake";
    }
}

Recommended Posts

Item 25: Limit source files to a single top-level class
How to decompile java class files
Item 23: Prefer class hierarchies to tagged classes
Transform from a normal class to a lambda expression
[Android] Inherit ImageView to create a new class
How to create a class that inherits class information
How to convert a solidity contract to a Java contract class