If you have a class called Foo and it is in a file called Foo.java then it is a top-level class. A top-level class can only have public or package level modifiers e.g.
- // Package level access. Only classes in the same
- // package as Foo have access to it.
- class Foo {
- }
- // This class can be accessed anywhere because it is
- // 'publically available'
- public class Foo {
- }
An inner class (or nested class) is one that is declared within the body of another class. (In Procesing any class defined inside a pde tab is an inner class). In the following example we have an inner class called InnerFoo
- public class Foo {
- public class InnerFoo {
- }
- }
Inner-class access-specifier (ICAS)
The ICAS can be public, protected, private or package level and have the same meaning as when they are applied to a class attribute or method.
private - only accessable from within Foo
protected - only accessable from within Foo or any class that inherits from Foo
public - global access
package - only accessible from within Foo or any class in the same package as Foo
If for some reason you wanted to create an object of type InnerFoo from outside of the Foo class then you would need something like this
Foo.InnerFoo ifoo = new Foo.InnerFoo();
provide the access-specifier allows you to see the class InnerFoo.
It is also possible to raise an inner class to a top-level class with the
static modifier e.g.
- public class Foo {
- public static class InnerFoo {
- }
- }
Now to create the InnerFoo object from outsde the Foo class you can do this
InnerFoo ifoo = new InnerFoo();
This is useful if you have a number of very small classes that perform a similar function, they can all be stored in a single source file but accessed like top-level classes. To see an example look at the
source code for the Validator class used in the GUI builder tool.
If i want the above private class TheThing to use in another class as well, do i have to copy and paste it then?
Never, ever do this just change the access modifier based on the access level required.