When To Use Inner Classes

In JavaLanguage, classes can be either top-level or inner, nested within another class. How do you decide whether a new class should be top-level or inner?

Forces for making an InnerClass:

Forces against making an InnerClass:


Is there a downside to avoiding Java InnerClasses in general? I only use them to simulate multiple inheritance (see BizarreLoveTriangleInJava) and function pointers (actually LexicalClosures), and I never use anonymous or static InnerClasses. Code without InnerClasses seems more readable and maintainable. JaredLevy

See InnerClasses


In Microsoft VisualCeePlusPlus you have to use InnerClasses when you want to imitate the functionality of PartialTemplateSpecialization?, which Microsoft have not implemented but which is necessary for many of the new C++ idioms.

  /////////example of using inner classes for PTS in CeePlusPlus ///////////
 template <class S, class T>
 struct Bar
 {
template <class U>
struct Foo
{
static int f(S s, T t){return 0;}
};
template <>
struct Foo<int>
{
static int f(S s, T t){return 1;}
};
typedef Foo<T> Imp;
 };
 template <class S, class T>
 int foo(S s, T t)
 {
return Bar<S,T>::Imp::f(s,t);
 }
  ////end of example of MSVC pseudo partial template spec. using inner classes /////////

Unfortunately I don't think the resulting code is strictly legal, but QuasiC++ aka MSVC seems happy enough with it.

BillWeston


EditText of this page (last edited December 2, 2005) or FindPage with title or text search