开发者

Purpose of an Inner Class?

I was reading some posts and noticed samples with an inner class. I've been seeing it a lot lately, particularly in a few examples on MSDN that I was browsing through. I've never had to use an inner class before (but maybe I really should be) so I wonder what exactly is the point? I assume that an inner class (at least a private one anyways) is only available to the main class itself, so wouldn't it be the same to simply incorporate whatever functionality the inner class has into some methods of the outer class? Is th开发者_JS百科ere an OO reason behind the inner class?

I'm thinking mainly within C#, but I suppose that this could apply to any OO language that supports an inner class.

Take this sample on msdn for example: CharacterCollection and WordCollection are public classes within the Document class. What difference would there be if these were outside of the Document class?


Inner classes are very useful if they only pertain to their containing (or, outer) class.

A good example of a private inner class is when you need to manage something within the outer class that will never be exposed. In the example below, a cache manager handles caching and uncaching of objects. It uses a private inner class to store the pointer to an object that it wants to cache, and also the time it was last accessed. Code that users this hypothetical CacheManager need never know about CacheEntry.

class CacheManager
{
private:
    class CacheEntry
    {
    private:
        Object* m_pObjectToCache;
        int     m_nTicksSinceTouched;
    }; // eo class CacheEntry
    std::map<int, CacheEntry*> m_Cache;

public:
    Object* getObject(int _id);
}; // eo class CacheManager

Then comes the case for a public inner class. I would use a nested class if the name (which I would like to keep simple), my conflict elsewhere:

class Tree
{
public:
    // public class.. Node might pertain to anything in the code, let's keep it simple
    // and clear that THIS Node belongs and works with THIS Tree class.
    class Node
    {
    };// eo class Node
}; // eo class Tree


One reason is that inner classes have access to the members of the enclosing class directly. They do not need a reference to the enclosing class in order to access those members. At the same time other objects may need access to the inner object.

I can think of the example of Iterators that are declared as inner classes in collections. The iterator needs to have intimate knowledge of the collection that it iterates but the client code needs access to the iterator itself as an object. You cannot take the functionality of the iterator and include it in the outer class.

Maybe the responsibilities of the outer class does not include those of the inner class directly. So creating the inner class helps to maintain highly cohesive classes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜