Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Declaration - public and default

Tags:

java

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?

like image 824
user2408664 Avatar asked Oct 16 '13 11:10

user2408664


2 Answers

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.

like image 93
Maroun Avatar answered Oct 22 '22 00:10

Maroun


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.

like image 35
Sajal Dutta Avatar answered Oct 22 '22 00:10

Sajal Dutta