-2

I saw this pattern today and it confused me a lot:

abstract class A {
    // does something

    static class B extends A {
        // does something as well
    }
}

Two weird things I found about it:

  • Static class can be initialised using new A.B().
  • Static class is not unique in the application (therefore, not really static), as each initialisation creates a new object.

I am still perturbed as to why to use such a pattern? And does static class in this context mean, that you can access it's constructors statically, without needing to create an instance of A, but not really it being a unique in any way in the app?

EDIT:

OK, so I think my understanding of static classes came from C#. I am clear on the staticness of java classes now. But when would you use such a pattern (where inner static class is extending outer abstract one) and why?

eddyP23
  • 6,420
  • 7
  • 49
  • 87
  • https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html –  Oct 05 '17 at 18:38
  • 2
    "Static class is not unique in the application (therefore, not really static), as each initialisation creates a new object." - that doesn't make more copies of the class itself, and that's not what "static class" means in Java anyway. Maybe you're thinking of C#. – user2357112 Oct 05 '17 at 18:38

1 Answers1

1

static class doesnt have access to the outer class methods and variables, they keyword kind of means that it is a separated class.

class Out {
     int i; void x(){}
     static class In() {
       i++; x(); // not valid instructions
     }
     class In2() {
       i++; x(); // valid instructions
     }
}

To instantiate a static inner class you just create a object of it:

  Out.In obj = new Out.In();

non-static needs a instance of the outer class to be instantiated with:

  Out o = new Out();
  Out.In2 obj = new o.In2();

(If instantiating In2 inside of Out the word this is implicit)

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167