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:
Thanks
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.