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

7
  • 3
    Where do you hear - You can't create instance of static class? and let me remind you, you can't have your top-level class static. Commented Aug 2, 2013 at 15:18
  • Are you confusing static with abstract? Commented Aug 2, 2013 at 15:18
  • How do you think Singletons work then? :) Commented Aug 2, 2013 at 15:19
  • 2
    @Shark with pure evil Commented Aug 2, 2013 at 15:20
  • 2
    If you are comparing it with C#. Static class in Java and C# are very different! Commented Aug 2, 2013 at 15:21

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

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();

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.