Sarath
Sarath

Reputation: 39

public and private class in the same file

I created a public and private class in the same java file. It is not getting compiled.

However, if I keep a public class and a class without any access modifier, it is gets compiled.

What is the reason for this ?

Upvotes: 3

Views: 6080

Answers (4)

Gursel Koca
Gursel Koca

Reputation: 21300

Toplevel private class is nonsense, because no other class can access this class. That is why you get compilation error..

JLS states that ;

The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration (§8.5) and are discussed in §8.5.1.

Upvotes: 11

Op De Cirkel
Op De Cirkel

Reputation: 29473

You can not declare class private unless is enclosed within another class. This is by specification, JLS - 8.1.1 Class Modifiers

Upvotes: 0

mopsled
mopsled

Reputation: 8505

If you try to create a .java file structured so that there are more than one public class definition or a private class definition in the root structure, as so:

public class SomeClass { ... }
public class SomeOtherClass { ... }

or

private class SomePrivateClass { ... }

there will be an error. However, you can define your private class within a public class class, like this:

public class SomePublicClass {
    private class SomePrivateClass { ... }
    ...
}

with only one base class within the java file, and this will compile.

EDIT: Corrected information about legal class structures based on Joachim Sauer's comment.

Upvotes: 5

trutheality
trutheality

Reputation: 23465

It's illegal to specify outer classes as private. Without the access modifier it takes the default of only being accessible from the same package.

More info: http://en.wikibooks.org/wiki/Java_Programming/Access_Modifiers

Upvotes: 2

Related Questions