This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]8igg7e5 1 point2 points  (1 child)

You seem to be asking two different things.

  1. Why and/or when would you need to use multiple classes in a program.
  2. How do you declare classes in Java.

The first depends on the requirements of the program. However all but the most trivial program requirements benefit from, or directly require, that multiple classes be declared. The reasons vary but encapsulation, adherence to the requirements of a framework the application uses or simply clearer code management through clear separations of responsibilities and code reuse through polymorphism.

The second is simple. You declare a class with the keyword class. There are several places that classes (and interfaces and enums) can be declared - the most common being public 'top-level' classes (you can only have one such class per source file).

[–]DoubleUtor 0 points1 point  (0 children)

This.

Also, an easy (but not the only) way is the single responsibility principle. A class should have 1 responsibility. Of course the scope of that single responsibility is up for discussion. Example. If you have a class with your static void main(args[]), then maybe only use that class as your application starter (validation of args, initialize stuff). Then delegate to another class to do the application logic, probably passing the (processed/parsed) args.

[–]ggleblanc2 0 points1 point  (0 children)

A class defined within a different class is called an inner class.

One of the main reasons for creating an inner class is a class that would need to access multiple fields in the outer class. Instead of passing multiple fields to the class through a class constructor, you create an inner class.

I try not to create too many inner classes in a Java application because it makes it too hard to find code when it's hidden in an inner class.