I would like to inquire if a class declaration in java can only be public
and default?
I have read that there can only one public
class inside a file and that file should be the name of the class.
For example Test.java
public class Test {
}
But I observed that in a class I can have no public
class but can have many default classes.
For example Exam.java
class Exam {
}
class Examination {
}
Why is it that I can only have one public
class but can have many default class inside one file?
Why is it that I can only have one public class but can have many default class inside one file?
7.6. Top Level Type Declarations:
This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a Java compiler to find a named class within a package. In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.
If a class doesn't have a modifier (default modifier), it can only be accessed from the same package.
This is a design decision as pointed out by another answerer. This helps you organize the code in long run. You can have public inner classes though.
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