5

Just a brief question: In all the examples I've seen in the android documentation, fragments are static inner classes. Is that a requirement of Android? Or can they be set up as regular inner classes? Is there someone out there who understands the internals of Android enough to provide an answer?

From what I've read in the OCJP documentation, these static inner classes are not suppose to be classes at all, but are just static members of the class in which they are contained, just like any static method - such as main.

Your insights are appreciated.

A--C
  • 36,351
  • 10
  • 106
  • 92
user1837057
  • 75
  • 1
  • 3

1 Answers1

9

Is that a requirement of Android? Or can they be set up as regular inner classes?

They cannot be regular (non-static) inner classes. Only an a instance of the outer class can create an instance of a regular inner class, and Android needs to recreate your fragments for you (e.g., on a configuration change). Fragments have to be either regular Java classes or static inner classes, and they need to have a public zero-argument constructor.

these static inner classes are not suppose to be classes at all, but are just static members of the class in which they are contained, just like any static method - such as main.

I have no idea how you came to that interpretation.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • This is taken from the book Sun Certified Programmer for JAVA 6 study guide, page 681: "The class itself isn't really static; there's no such thing as a static class. The static modifier in this case says that the nested class is a static member of the outer class. That means that it can be accessed, as with other static members, without having an instance of the of the outer class". This true of a main method, since it is static. But your comment helps. Thanks. – user1837057 Feb 24 '13 at 13:26
  • 3
    @user1837057: I disagree with the explanation from that study guide. IMHO, static inner classes are pretty much just syntactic sugar for namespacing -- in most other respects, they are no different than regular Java classes. – CommonsWare Feb 24 '13 at 13:29