views:

72

answers:

3

Hello.

I want to create a class, ClassB, as inner class of ClassA, but I want to write down outside ClassA.java file.

How can I do this?

It will be a lot of inner class, and ClassA.java file will be enormous.

UPDATE
What I really want to do is define ten classes that they will be only accessible by one class. All of them are defined inside the same package.

Thanks.

+7  A: 

The simple answer, is no you cannot.

By virtue of being an inner class, the class has to be inside the scope of the parent class.

If your class is really going to be enormous, it probably says something about the design of your class. Are you making proper use of encapsulation?

Codemwnci
Ok. What I really want to do is define ten classes that they will be only accessible by one class. All of them are defined inside the same package.
VansFannel
You need to contain all your classes inside a package, and make your classes package wide, so they cannot be accessed outside of the package.
Codemwnci
+2  A: 

UPDATE
What I really want to do is define ten classes that they will be only accessible by one class. All of them are defined inside the same package.

If you want to restrict access to a single class, you can put them all in a new package. You will need to move the designated class that is allowed access into this packate, too. For the new classes, you can restrict access by using the default access level (no public/private/protected modifier). This will make them accessible only to the classes in their package. The specified class that is allowed access can be made public so that it can be used outside this new package.

Note: You have the option of restricting the visibility of the class or the visibility of the constructor.

akf
+1 for private constructors as an option.
Jeremy
moving packages around is not a good solution, it restrict the use in packages. if the question is for one shoot program, that no one cares about, then it could be a good solution.
none
+4  A: 

Put all your classes in a package and define the classes to be package private.

package com.example.here

class Hello{
    //...
}

Notice the absence of the keyword public? You will only be able to create the class Hello if the class creating it is in the com.example.here package.

Jeremy