1

Is it possible to create a class within the same file that contains the main method? A programming contest that I'm practicing for only accepts a single file as a solution so I can't write the class in a separate file and send it in.

I know you can create inner classes but does it provide the same functionality as normal classes?

rEgonicS
  • 201
  • 2
  • 4
  • 8

4 Answers4

2

Yes, you can define multiple top-level classes in a single .java file. See Java: Multiple class declarations in one file

For most purposes nested classes should work just as well. You may want to declare such classes static to avoid the implicit reference to the outer class.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • By definition, inner classes are non-static nested classes. Static nested classes are called just that. :-) – C. K. Young Jul 19 '11 at 05:33
  • @Chris Jester-Young: fair point, I didn't realize my terminology was a bit off. Fixed. – NPE Jul 19 '11 at 05:35
0

You have always a Class holding a main method but you may also put inner classes into this class too.

Something like this:

public class A {

   protected class B {
   }

   public static void main(String[] args){
   }
}
fyr
  • 20,227
  • 7
  • 37
  • 53
0

Inner classes can't have static methods, so you can't have main there. However, static nested classes can indeed have main.

Also, as aix's answer says, you can also have multiple package-private top-level classes in the same source file.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
0

It is 100% valid from the compiler point of view to have several classes in single source file. I use this feature often to create object hierarchy in single screen and refactor the classes and interfaces to their own source files later. Please remember that only one class in source file could be public.

public class Runner {
    public static void main(String[] args){
       new A().process();
    }
 }
class A{
    public void process(){
      ...
     }
}
ya_pulser
  • 2,620
  • 2
  • 16
  • 21