Is it possible to have a private class?

前端 未结 4 1252
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 13:40

I always wonder if it is possible to have a private class? And, what would be the point of having such class?

Thanks for helping.

4条回答
  •  逝去的感伤
    2021-01-12 13:54

    Yes it is possible to have a private class, but only as an inner class of another class:

    public class Outer
    {
        private class Inner
        {}
    }
    

    This is usually useful when you want to encapsulate some logic inside of a class (the outer one), but need a more structured/OO design of code to implement it. I have used this pattern in the past when I need a container class to process some information within a method of a class, but the container class has no meaning outside of this logic. Making the container class a private inner class means that its use is localised to the outer class that utilises it.

    It is worth noting that with this structure, the inner class has access to the private members of the outer class, but not the other way around.

提交回复
热议问题