Java中能否定义无main()方法的类并通过其他类调用?
Absolutely! Java totally supports this pattern—it’s actually the standard way to structure real-world Java applications, just like you’re used to in C++. The reason you might see main() in every class in some tutorials is usually for standalone demonstration purposes, but in real-world projects, most classes won’t have a main() method at all.
Let me show you a concrete example to make this clear:
A class without a main() method (your core logic class)
public class Book { private String title; private String author; // Constructor public Book(String title, String author) { this.title = title; this.author = author; } // A method to display book details public void showDetails() { System.out.println("Title: " + title + ", Author: " + author); } }
A separate class with main() (the program entry point)
public class LibraryApp { public static void main(String[] args) { // Create an instance of the Book class (no main() there!) Book myBook = new Book("The Great Gatsby", "F. Scott Fitzgerald"); // Call the method from the Book class myBook.showDetails(); } }
When you run LibraryApp, the JVM will use its main() method as the starting point, create a Book object, and execute its showDetails() function—exactly the workflow you’re familiar with from C++.
Here are a few key notes to keep in mind:
- You only need one
main()method per application—it’s the JVM’s entry point to launch your program. - Most classes in a Java project are focused on specific responsibilities (holding data, implementing business logic, providing utilities) and don’t need a
main()method. - The
main()method must follow this exact signature:public static void main(String[] args)—this is what the JVM looks for to start execution.
So rest easy—you’re thinking about this the right way. This is the industry standard for building clean, scalable Java code!
内容的提问来源于stack exchange,提问作者daydayup

