r/javahelp • u/Miserable_Bar_5800 • Jan 29 '26
Can I have 2 public classes?
Guys can anyone teach me?
We all know:
public class Main {
Whatever we put after public class it needs to be the file name, like in that it needs Main.java
What if we add two public classes like:
public class Main {
}
public class ootherMain {
}I'm just curious on what happens I think it gets an error or is there a way to actually do that?
0
Upvotes
View all comments
Show parent comment
1
u/severoon pro barista Jan 29 '26
In general, avoid public inner classes.
One good reason to use inner classes is when you want to make the inner class available to clients and you want the JVM to manage an implicit this reference to the outer class. Even then, it's sometimes better to prefer just making the class a normal class and manage that relationship to the outer class explicitly.
The problem with inner classes is that they make the outer class part of the inner class' namespace, and the inner class becomes part of the outer class' API, so really, these are the equivalent of friend classes in C++. Basically, these are two classes that depend upon each other, and you should think of them as the same class. But you're splitting them into two separate class APIs which implies that they have some kind of distinction.
In general, it's good to avoid cyclic dependencies at every level in your codebase, and that also applies to classes (even at the method level within a class API, really). Inner classes require a cyclic dependency between inner and outer.
The main use case for inner classes is when a class needs a quick implementation of an interface or abstract class, and it doesn't make sense to use an anonymous inner class or functional style, like maybe you need multiple instances. This might be an acceptable use of inner class, but in general I would even steer away from this because the fact that you can't just inline it means that this inner class you're creating probably has nontrivial functionality and needs to be tested, so it shouldn't be private. Also, if it evolves over time and collects more functionality, that's another reason it should just be a package-private peer class, or potentially even needs to be split out into a subpackage.