开发者

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.

Howe开发者_JS百科ver, if I keep a public class and a class without any access modifier, it is gets compiled.

What is the reason for this ?


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.


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜