Home > database >  Inner class does not have access to <T> of the outer interface
Inner class does not have access to <T> of the outer interface

Time:10-24

I am trying to follow the approach given in this answer of my earlier question:
But the code does not compile:

public interface Processor <T> {
     class Builder {
        private T t = null;  // assign default values
        private String firstName = null;
        private String lastName = null;
        private String cc = null;
    }
    List<Person> process();
}  

I get the error

com.foo.Processor.this can not be referenced from a static context 

How can I make the code compile so I can try out the approach of that answer?

CodePudding user response:

Processor is not a class, it's an interface. Nested classes in interfaces are static by default.

But the builder does not define any logic. Move the builder to the implementation (classes) of the interface.

public class RealProcessor<T> implements Processor<T> {
     class Builder {
        private T t = null;  // assign default values
        private String firstName = null;
        private String lastName = null;
        private String cc = null;
    }
    List<Person> process();
}

CodePudding user response:

You will need to make static class Builder generic if it is declared inside the interface:

public interface Processor <T> {
    class Builder<T> {
       private T t = null;
       // ...
    }
    // ...
}

Note that as Builder is a static class the name of the generic does not need to be <T>, this is an equivalent declaration using <X>:

public interface Processor <T> {
    class Builder<X> {
       private X t = null;
       // ...
    }
    // ...
}

The instantiation for both is same without need to qualify Processor generic type:

Builder<SomeClass> builder = new Processor.Builder<SomeClass>(arg, ... );
  • Related