Marut Goel
Marut Goel

Reputation: 29

Nested package in Java

Does Java allow nested packages?If yes then why outer class cannot be private? Scope of private outer class will be within that inner package and scope of default modifier will be outer package?

Like

{ // Outer Package

// Scope of default Access Modifier


    {  // Inner Package

       // Scope of private class

        private class Abc{



        }


        class Bcd{

        }

    }

}

Upvotes: 2

Views: 1631

Answers (2)

sdumont
sdumont

Reputation: 99

No nested packages do not exist in Java.

However, their is the case where there will be a class in the package such that the package path would look like this:
com.foo.Bar

And then there could exist further package directories under it such that another class's package path could look like this:
com.foo.boo.Lou

Oracle's Documentation here's a link provides a good overview of access control for classes.

This one here explains when to use nested classes and I think would give you a better explanation which I'll quote below:

Use it if your requirements are similar to those of a local class, you want to make the type more widely available, and you don't require access to local variables or method parameters.

  • Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.

And Here's a supplemental link to some more information on the differences between class types and package privacy.

Hope this helps.

Upvotes: 1

gagarine
gagarine

Reputation: 76

According to the doc, it is not possible:

The package statement (for example, package graphics;) must be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

Upvotes: 1

Related Questions