Is it possible to contain several classes and interfaces to them in one Java file? What is the best way to organize their structure, if you need to use them all (for example, 4 classes and interfaces)?

  • I work with Eclipse, and he creates a new class in his java file. - chudo116
  • one
    But is it a good idea to define several classes in one file? - G71
  • one
    is a bad tone - Anton Feoktistov

3 answers 3

// файл public class MainClass { // скрытый внутренний класс. Виден только внутри класса MainClass. private class MyInnerClass { } // скрытый интерфейс. Доступен внутри класса MainClass. private interface MyInnerInterface { } // Доступен везде, но создан может быть только изнутри MainClass public class MyPublicInnerClass {} // Доступен везде. Может быть создан в статическом контексте. // В отличие от обычных inner-классов, не имеет доступа к членам MainClass. public static class MyStaticClass {} } // класс доступен в рамках пакета class TestClass { } // интерфейс доступен в рамках пакета interface TestInterface { } 

Just keep in mind that the TestClass and TestInterface classes will be package-private, i.e. will only be visible within the package.

However, these possibilities should not be abused. Use them with care and as far as possible take the classes into separate files.

  • one
    cy6erGn0m +1 wrote everything correctly =) - Kobayashi_Maru
  • To @AleXpi Plus by clicking on the thumb up icon. - avp

Yes you can, but not worth it.

  1. Why is it NOT worthwhile to push the interface into the same file - because the interface itself implies that other people will use it, otherwise there is no sense from it?
  2. Why you should NOT push classes into the same file - because people will not know how to find this class (it’s only in universities that the code is written and fixed by 1 person).
  3. Why it is worth pushing classes into the same file - if you look at the source code in Java, you will find many examples where the abstract class is declared public, and its default implementation is in the same file. It makes no sense to take this class to a separate file. It is not provided that someone will use it, it is only needed by this public class.

It is worth noting, however, that usually these classes are netst classes in relation to the class declared as public.

    cy6erGn0m wrote absolutely everything) It remains only to add that it is better not to sculpt several classes in one file. This reduces the readability of the code, and after compiling into bytecode, you still get three files: MainClass.class, MainClass $ TestClass.class, MainClass $ TestInterface.class.

    • static interface did not write - was too lazy :) - cy6erGn0m