0

I was trying to include two different public classes in one .java file but that did not run, and searching on stackoverflow gave me the answer that two top level classes cannot be in one .java file.

But the same class with default access run smoothly, Why is it so?

Book Of Zeus
  • 49,509
  • 18
  • 174
  • 171
Mrak Vladar
  • 598
  • 4
  • 18
  • you can't create 2 files? create an inner/nested class maybe? – Book Of Zeus Feb 19 '19 at 05:37
  • I can do that, but I wanted to know what exactly is happening with the compiler why does it let default access class pass and not public classes. – Mrak Vladar Feb 19 '19 at 05:38
  • 1
    you might want to check this one: https://stackoverflow.com/questions/3578490/why-only-1-public-class-in-java-file – arjayosma Feb 19 '19 at 05:40
  • 2
    Fully qualified name (file path based) is required to access public classes, because they can be accessed from anywhere. Whereas package-private classes are visible inside the package and don't need to be imported. I don't have a reference to support this, hence not posting it as an answer. – Kartik Feb 19 '19 at 05:42
  • thanks @arjayosma but that does not talk about two default classes residing in one .java file – Mrak Vladar Feb 19 '19 at 05:42
  • See https://docs.oracle.com/javase/specs/jls/se10/html/jls-7.html#jls-7.6, particularly the conditions in the bullet list. – chrylis -cautiouslyoptimistic- Feb 19 '19 at 05:44
  • thanks @Kartik, that's actually what I was expecting. – Mrak Vladar Feb 19 '19 at 16:48

0 Answers0