Any possibility to divide a class into multiple physical files using Java?
Of course you can separate out 2 classes and still they will work fine. Just make sure you import one class in another using import statement. All you need to do is move AnotherClass class into a separate source file named with name same as class name ie "AnotherClass.
It is technically legal to have multiple Java top level classes in one file. However this is considered to be bad practice (in most cases), and some Java tools may not work if you do this.
No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public. If you have more than one public classes a single file a compile-time error will be generated.
If you have a class that really needs to be a separate class but is also only used in one place, it's probably best to keep it in the same file. If this is happening frequently, though, you might have a bigger problem on your hands.
No, the whole of a class has to be in a single file in Java.
If you're thinking of C#'s "partial types" feature, there's no equivalent in Java. (If you weren't thinking of C#, ignore this :)
For the sake of completion:
Since Java 8, you have the concept of default methods.
you can split up your class into multiple files/subclasses by gently abusing interfaces
observe:
interface MyClassPartA{
public default int myMethodA(){return 1;}
}
interface MyClassPartB{
public default String myMethodB(){return "B";}
}
and combine them:
public class MyClass implements MyClassPartA, MyClassPartB{}
and use them:
MyClass myClass = new MyClass();
System.out.println(myClass.myMethodA());
System.out.println(myClass.myMethodB());
You can even pass variables between classes/files with abstract getters and setters that you will need to realize/override in the main class, or a superclass of that however.
This might be a good idea if the class is really so large such that the implemented concepts are not easy to grasp. I see two different ways to do this:
Use inheritance: Move general concepts of the class to a base class and derive a specialized class from it.
Use aggregation: Move parts of your class to a separate class and establish a relationship to the second class using a reference.
As previously mentioned, there is no concept like partial classes in Java, so you really have to use these OOP mechanisms.
Using just javac
, this is not possible. You could of course combine multiple files into a single .java file as part of your build process, and invoke javac
afterwards, but that would be cumbersome on so many levels that it is unlikely to be useful.
Maybe you could explain your problem, then we can help better.
If you feel your .java files are too large, you should probably consider refactoring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With