Search code examples
javaandroidpreferenceactivity

Subclass contained in parent class


Looking through some source code for a Settings App I found something that ressembles what you see below, where there are child classes of a class mentioned within the original class. These classes are not abstract and have no body.

public class mySettings extends PreferenceActivity {
...
//Class definition
...
public static class myColorSettings extends mySettings {/*empty*/ }
public static class myConnectSettings extends mySettings {/*empty*/}
}

In the actual app, there are buttons "My Color" and "My Connect" that each open up new activities (or fragments if the screen is dual pane).

So I have two questions: what is the use of declaring subclasses within a class itself - from an Object Oriented programming point of view - as shown above? And my second question is, if the classes are clearly empty and not abstract, but the end result is not empty, what is the use of these empty declarations?

EDIT 1

As pointed out in the comment, the Android repo has a nearly identical setup. See the link http://tinyurl.com/nbkv7zg (around line 1070)


Solution

  • Here is Oracle's answer to your first question:

    Why Use Nested Classes?

    Compelling reasons for using nested classes include the following:

    •It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

    •It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

    •It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

    Source: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

    Without seeing the rest of the project's code, my best guess would be that those two classes, although empty, must be declared as required by some part of the PreferenceActivity parent class.