The only restriction against placing multiple classes inside the same file when compiling Java is that only one top-level class in the file can be marked public
. This is because public
classes must be in a file with the same name, and you can't have multiple classes with the same name.
It's usually a considered a poor practice, and it doesn't guarantee your classes will have the correct protection level, but you can just leave off public
when declaring your additional classes. This will give them default
protection.
For a good discussion on what default protection means (and the other protection levels), just see this question.
So you could create the file UsernameAlreadyTakenException.java
and put in it something like:
public class UsernameAlreadyTakenException extends Exception {
...
}
class MySecondException extends Exception {
...
}
...
class MyNthException extends Exception {
...
}
You could even name the file something else, but then you can't have the class UsernameAlreadyTakenException
marked as public
. But once again, it is frowned upon to do this. It's usually just better to have a new file for each distinct class.