Why would one use nested classes?

霸气de小男生 提交于 2019-12-12 12:06:35

问题


Been doing objective-c for 5 years, so please bear with me.

I'm struggling to find documentation that clearly explains why you would want to nest a class definition, inside of another.

If I had two classes like the following, it makes sense to me that they are declared above and below each other. You may even want to have a nested property that references the other.

class DataImporter {
     }

class DataGenerator {
     }

But I don't understand why a nested arrangement like the following would be useful.

class DataImporter {
     class DataGenerator {
     } }

回答1:


You would do that for Namespacing. This way you can have the classes with the same name (like DataGenerator). But for different purposes. This one would be DataImporter.DataGenerator class, but you could have another OtherClass.DataGenerator class which would be a totally different one.

Like in Objective-C when you had 2 or 3 letters before the name of the class (ex: UIView). But when you created your own, it would be like SSView

You can also declare the inner class private and use it just in that file.



来源:https://stackoverflow.com/questions/35947901/why-would-one-use-nested-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!