You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中能否定义无main()方法的类并通过其他类调用?

Does Java support classes without a main() method that are called by other classes?

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:49:40