I have Servlet that looks something like this:
public class MyServlet extends Servlet {
private class Page {
private Page(HttpServletRequest request, HttpServletResponse response) {
/* Do stuff */
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
Page page = new Page(request, response);
/* Do other stuff */
}
}
I also have a Cache that looks something like this:
public class Cache {
private Hashtable<String, CacheValue>;
public Cache() {
Hashtable<String, CacheValue> table = new Hashtable()<String, CacheValue>;
}
public void put(String key, String value) {
table.put(key, new CacheValue(value));
}
private class CacheValue {
private value;
private CacheValue(String value) {
this.value = value;
}
}
}
My question is this: is there anything wrong with using private nested classes in this way? I know that you'd usually have a separate public class in a separate file, but a CacheValue
is only ever used by a Cache
. A Page
is only ever used by a MyServlet
. Organizing the classes this way makes sense to me, but I'm no old pro at Java, so I'm interested in the pros and cons.
Is using nested classes generally regarded as a matter of style? Or of preference? Or something to be avoided? Or a tool to reduce complexity?