0

I'm reading 'Thinking of Java' and I have encountered some weird example (for me)

class StaticTest {
    static class StaticClass {
        int i = 5;
    }
}

public class I {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        StaticTest.StaticClass t = new StaticTest.StaticClass();
    }

}

How is it possible to create instance of static class? Is it some exception to the rule 'You can't create instance of static class'?

Thanks in advance

tomwesolowski
  • 956
  • 1
  • 11
  • 27

4 Answers4

1

In case of classes, the modifier static describes the relationship between the outer and the inner class.

If the inner class is not static, it is bound to an instance of the outer class and threrefore cannot be created from outside.

A static inner class can completely be created without an instance of the outer class, but has privileged access to members of the class.

0

A static class is nothing more than a class, but with the difference to where it's code is placed.

Therefore, you can create instances of static classes. The only difference is you have to provide the name of the class, which nests the static one (as shown on your code snippet).

StaticTest.StaticClass t = new StaticTest.StaticClass();
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

From Java docs regarding creating instance for static nested classes.

And like static class methods, a static nested class cannot refer directly to instance     
variables or methods defined in its enclosing class — it can use them only through an  
object reference.

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Vikas V
  • 3,176
  • 2
  • 37
  • 60
0

in this case static describes the relation b/w inner and outer class

it doesnt mean the inner class is static

a static nested class doesnt invoke non-static methodes or access non-static fields of an instance of class within which it is nested

sandiee
  • 153
  • 1
  • 8