0

I was just checking inner classes and I know we can declaired the private and static inner class however I do not under stand what can we achieve by declaring a inner class private and static.

class OuterClass {

    private static class InnerClass{
    }
}

As this class is private no other class would be able to access InnerClass so Static would not help I think.

Is it just allowed for simplicity in java

Sandesh Dhotre
  • 33
  • 1
  • 11
  • 1
    `static` means you don't need an instance of `OuterClass` to construct an `InnerClass`. Consider `public static InnerClass buildInner() { return new InnerClass(); }` – Elliott Frisch Nov 15 '19 at 04:41
  • Elliott Thanks for the information however you mentioned public static class which I know we can use to instantiate a inner class outside however I was asking for private static class as private class is static we can not use the advantage of it is being static – Sandesh Dhotre Nov 15 '19 at 05:10
  • ['Static inner' is a contradiction in terms.](https://docs.oracle.com/javase/specs/jls/se13/html/jls-8.html#jls-8.1.3) There is no inner class here. – user207421 Nov 15 '19 at 06:49

2 Answers2

1

Although Elliot Sir and Sambit have given hints, I provide the below an where we use private static inner class. We can create a Singleton class which is thread-safe and immutable also.

public class Singleton  {    
    private static class Holder {    
        public static final Singleton INSTANCE = new Singleton();
    }    

    public static Singleton getInstance() {    
        return Holder.INSTANCE;    
    }    
}

It is called initialization on holder pattern.

https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom

PythonLearner
  • 1,416
  • 7
  • 22
  • Hi Dabadatta Thanks for the info I think this makes much better sense I will need to read more about this design patter and what are the advantages of this. Thanks for the information – Sandesh Dhotre Nov 15 '19 at 06:14
0

By making it static, you make it not require an object. It is still available to other code within the outer class, such as static methods.

Matt
  • 560
  • 1
  • 5
  • 12