private abstract classes in Java

I am a relative newcomer to Java. I recently came across a private static abstract class inside a regular class while browsing some Android app source code. What could be a use case for such a nested class? How would it be used and what sort of design benefits are there from using such a class?

Jon Skeet
people
quotationmark

I've never come across this pattern before myself, but I can imagine it being useful if:

  • You want to implement an interface in a similar way in a bunch of nested classes (e.g. to be returned from public methods within the enclosing class)
  • Those interface implementations have a lot of code in common (hence the abstract class)
  • You don't need any code other than the implementations to know about the abstract class

The subclasses of the abstract class may well be private as well. (Typically when I write nested classes, they're private implementation details.) For example:

public interface Foo {
    // Methods here
}

public class FooFactory {

    public static Foo getFoo1() {
        return new Foo1();
    }

    public static Foo getFoo2() {
        return new Foo2();
    }

    private static abstract class AbstractFoo implements Foo {
        // Implement methods in Foo in terms of 
        // doSomething()...

        // Implementation-specific method
        public abstract void doSomething();
    }

    private static class Foo1 extends AbstractFoo {
        public void doSomething() {
        }
    }

    private static class Foo2 extends AbstractFoo {
        public void doSomething() {
        }
    }
}

people

See more on this question at Stackoverflow