Subclass contained in parent class

54 views Asked by At

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)

2

There are 2 answers

0
AngelTrs On BEST ANSWER

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.

0
Gerald Mücke On

I'd call this generally a bad design.

Nested classes may be used as alternative to organizing them in a package, especially when their use is limited to or make only sense in the context of the containing class. If they are used outside, refactor them out.

As both classes are obviously empty, they are a complete waste and could be removed. Instead, each instance of the parent class could be used in a different role

mySettings colorSettings = new mySettings();
mySettings connectSettings = new mySettings();

Btw. starting the name of a class with lower case is a bad practice