File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Static class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Static class" Watch "Static class" New topic

Static class


Joined: Oct 05, 2000
Posts: 1
What is a static inner class. When do we use it.
swapnil dey

Joined: Sep 25, 2000
Posts: 18
hi srinivas
first bout an inner class, it is a class defined within another class. now to create instances of the inner class u need an instance of its containing class.. i.e given a class Outer that contains another class Inner, to create an instance of Inner u must use
a)Outer o = new Outer();
Inner in = Inner();
b)Outer.Inner in = new Outer().new Inner();
but a static inner class doesn't need an outer class instance, the following code would work for a static inner class, but not for one which isn't static
Outer.Inner in= new Outer.Inner();
but as far as the usage is concerned, its something even i need help on....
swapnil dey
Alex Fon

Joined: Oct 17, 2000
Posts: 1
example of my usage:
I have class Errors for all error numbers definitions. All numbers are defined as static members to have access without creating class instance.
Now I want some errors hierarchy: for example separate Login and NewUser errors:
public class Errors
public static final int UNEXPECTED = 0;

public class Login
public static final int PASSWORD_DOESNT_MATCH = 1;
public static final int USER_DISABLED = 2;
public static final int USERSELF_DISABLED = 3;
public Login(){};
public static Login jspLogin;

public class NewUser
public static final int SOME_FIELDS_MISSED = 1;
public static final int CANNOT_SAVE_TO_DB = 2;
public NewUser(){};
public static NewUser jspNewUser;
example of usage:
if (myError == Errors.jspLogin.PASSWORD_DOESNT_MATCH)
swapnil dey

Joined: Sep 25, 2000
Posts: 18
hi alex
can't we do the same thing by extending the classes Login & NewUser from the class Error.
any specific reason why inner classes be given preference over inheritance
swapnil dey
Rob Whelan
Ranch Hand

Joined: Oct 18, 2000
Posts: 33
Static inner classes are also called "nested" top-level classes, because, they're basically the exact same thing as a top-level class.
The only reason for using one is organizational, as far as I know. For instance, you might have a class that doesn't need the usual inner class privileges, but will only ever be used by the class containing it.
Correction: I forgot that static inner classes have access to static members of the enclosing class -- including private static members. Also, the enclosing class has the same access into the inner class. More details here.
[This message has been edited by Rob Whelan (edited November 02, 2000).]
I agree. Here's the link:
subject: Static class
It's not a secret anymore!