Parameterizing superclass with static member class from subclass

  • A+
Category:Languages

Is there a way to parameterize a superclass with a static member class of the subclass?

Contrived Example

ExampleSuperClass.java:

package foo;  public class ExampleSuperClass<T> {     protected T field;      public ExampleSuperClass(T field) {         this.field = field;     }      public T getField() {         return field;     } } 

ExampleSubClass.java:

package foo;  public class ExampleSubClass extends ExampleSuperClass<Member> {      static class Member {      }      public ExampleSubClass() {         super(new Member());     } } 

Compilation fails on ExampleSubClass.java with error:

[javac] ExampleSubClass.java:3: error: cannot find symbol [javac] public class ExampleSubClass extends ExampleSuperClass<Member> { [javac]                                                        ^ [javac]   symbol: class Member [javac] 1 error 

or in Eclipse with:

Member cannot be resolved to a type

in Eclipse the super invocation also has the error:

The constructor ExampleSuperClass(Member) refers to missing type Member

It works fine (aka no errors) if ExampleSubClass is instead parameterized with another package-protected top-level class.

Summary

The driving force behind this is that I have a generic super class and many different ${SubClass-extends-GenericSuperClass}.java and ${ClassUsedBySubClass}.java pairs. But since ClassUsedBySubClass is only ever referenced by SubClass, it would be nice to:

  1. restrict ClassUsedBySubClass's access by making it a static member class and
  2. cut down on the number of files by not giving ClassUsedBySubClass its own file.

So, is there a way to use a subclass's member class in parameterizing the superclass?

If there isn't -- is there an alternative approach?


Yes, you can do it. However, since Java uses the scope outside the declaration for name resolution, you must qualify Member with the name of ExampleSubClass:

public class ExampleSubClass extends ExampleSuperClass<ExampleSubClass.Member> {     ... } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: