Search code examples
javaspringdependenciesguicecode-injection

Given ClassA and SubclassA, if I use Google Guice to bind ClassA to SubclassA then will SubclassA be injected as an instance where ClassA gets called?


Say I am given a scenario like this:

@Data
public class ClassA {
     private final String name = "ClassA";
     public ClassA(){
       //This constructor gets called anyway. Why?
     }
}


@Data
public class SubclassA extends ClassA {
     private final String subname = "SubclassA";
     @Inject
     public SubclassA(){
        //I would expect for ONLY this constructor to be called.
     }
}


public class MyModule extends AbstractModule {
     @Override
     protected void setup(){
       bind(ClassA.class).to(SubclassA.class);
     }
}


public class Main {
     public static void main(String [] args){
       Injector injector = Guice.createInjector(new MyModule());
       ClassA classA = injector.getInstance(ClassA.class);
     }
}

Some of my questions:

  • Why are both constructors called?
  • Is the object classA an instance of ClassA or SubclassA?

Thanks


Solution

    • Is the object classA an instance of ClassA or SubclassA? Strictly sparking, classA's type is SubClassA.

    • Why are both constructors called? Because SubClassA is a subclass of ClassA, when creating an instance of SubClassA, its parent class's constructor is also called.