0

The following sample code is from website.

sInstance is a private member, it means that it's only be access in the class LittleMonkProviderHolder.

Why can the function getInstance() return LittleMonkProviderHolder.sInstance ? Thanks!

Code

public class FloatActionController {

    private FloatActionController() {
    }

    public static FloatActionController getInstance() {
        return LittleMonkProviderHolder.sInstance;  //Return a private member!!!
    }


    private static class LittleMonkProviderHolder {
        private static final FloatActionController sInstance = new FloatActionController();
    }

}
Kartik
  • 7,677
  • 4
  • 28
  • 50
HelloCW
  • 843
  • 22
  • 125
  • 310
  • the concept of access scopes is rather self-explanatory, when looking what the keywords exactly mean. – Martin Zeitler Oct 26 '18 at 03:23
  • 1
    @MartinZeitler You might want to read the question again. It's a valid question, why can a private member be accessed by it's outer class. – Kartik Oct 26 '18 at 03:24
  • @Kartik keyword `private` has access level `class`: https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html - this can be an advance and dis-advance of inner classes, depending what one intends to accomplish. – Martin Zeitler Oct 26 '18 at 03:27
  • Ah, I missed the key aspect of this question upon initial skimming. Indeed, the question is asking _"why is a (static) inner class private instance visible to the outer class."_ I was expecting the basic "type vs instance" question & crafted a useless explanatory answer before reading more closely. – michael Oct 26 '18 at 04:41
  • looks like you are missing java basics. Take some time to go through some basic java tutorial to eliminate similar future questions. – Vladyslav Matviienko Oct 26 '18 at 04:52

1 Answers1

2

This looks like a Bill Pugh singleton to me. There is nothing wrong with returning a private member from a private inner class in the FloatActionController class. The private specifier only means that trying to access the field directly via:

FloatActionController.LittleMonkProviderHolder.sInstance

would fail, as both the inner class and its member are private.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360