I’m implementing a system where I have an interface named ‘MyMethod’ (the name is arbitrary), and lots of small classes are implementing this method (specifically to override it’s ‘call’ method), and I’m using polymorphism to create instances of these into a list.
The thing is, as I have lots of these small classes implementing the method, it was easier to put these classes in the same java file (MyMethod.java), like so:
public interface MyMethod {
public String call(foo param1, bar param2) throws SQLException, IOException;
}
class FooMethod1 implements MyMethod {
@Override
public String call(foo param1, bar param2) throws SQLException, IOException {
//Do Something
}
}
class FooMethod2 implements MyMethod {
@Override
public String call(foo param1, bar param2) throws SQLException, IOException {
//Do Something Different
}
}
However, putting these classes in the same file, although neater, seems like I’m going against the way things should be done in Java.
Is it okay to have these classes in the same file? or should I move them each to a separate file?
Thanks
Yes, it is ok to put several package-private classes in the same file.
The relevant section of the JLS is §7.3
As you can see, a compilation unit may have several type declarations (or zero). Another relevant section of the JLS is §7.6. It explains the correlation between those type declarations that are accessed from outside of a compilation unit, and the compilation unit’s file name:
Clearly, your approach isn’t against Java and perfectly OK. However, beware that your
MyMethodimplementations may not be available outside of theMyMethod.javacompilation unit, depending on the compiler implementation. Although, neither javac nor the Eclipse compiler seem to have issues with this…