0

is there a way to declare 2 classes on the same .java file using Eclipse - also how the compiler will distinguish the .class for each declare class.

example

public class ThisTest
{
    public static void main(String[] args)
    {
    }
}

class SimpleArray
{

}

thank you for your time.

aioobe
  • 413,195
  • 112
  • 811
  • 826
Sinan
  • 453
  • 2
  • 10
  • 20
  • possible duplicate of [Java: Multiple class declarations in one file](http://stackoverflow.com/questions/2336692/java-multiple-class-declarations-in-one-file) – talnicolas Mar 20 '12 at 19:24

2 Answers2

3

is there a way to declare 2 classes on the same .java file using Eclipse

Yes, you can have several classes defined in a single .java file, but there may at most one public class in each file. (Just as in your example.)

Note that if you have a public class in a .java file, the name of that class must be the same as the name of the .java file.

how the compiler will distinguish the .class for each declare class.

The names of the .class files does not depend on the name of the .java file, but on the identifiers of the class declarations.

If you have

class A {}
class B {}

in a file named Classes.java, you'll get A.class and B.class if you compile it.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Thank you, but my question is there is way to do that !! you can see from the above code, Class thisTest is declare public and Class SimpleArray is a declared by default !! – Sinan Mar 20 '12 at 19:28
  • Thank you for the explanation it is really helpful.. now that I have the 2 classes declared on the same file I got in compilation error "The public type Class ThisTest should be defined in its own file" ? any solution to this ? – Sinan Mar 20 '12 at 19:32
  • Yes, *if* you have a public class, the name of that class must be the same as the .java file name. – aioobe Mar 20 '12 at 19:41
  • @Sinan. This error means that the name of your .java file does not match the name of the public class. For your example above, the file MUST be called ThisTest.java – Jochen Mar 20 '12 at 22:59
1

Yes, exactly like your example.

The extra class need to be non-public

You could also define inner/nested classes. In this case you should investigate the difference

Java inner class and static nested class

public class ThisTest
{
    public static void main(String[] args)
    {
    }


    static class SimpleArray
    {

    }

    class SimpleArray2 {}
}
class Buddy {}

Each class will be located in an own .class file in a directory similar to the package. Nested classes get its host prefixed and separated by an '$'. The above case results in four class files

  • ThisTest.class
  • ThisTest$SimpleArray.class
  • ThisTest$SimpleArray2.class
  • Buddy.class

Just check the bin or classes folder of your eclipse project.

Community
  • 1
  • 1
stefan bachert
  • 9,413
  • 4
  • 33
  • 40