I’ve never studied Java in depth. Lately, I had to deal with a behaviour that I’d like to investigate, because I haven’t fully understood it.
Can you explain to me why the main package does not need to import the package b? Although the the argument of aa method is B type.
This code works properly.
Can this particular case be seen as in-line dependency Injection?
package c;
import b.*;
public class C {
B b=new B();
public B cc(){
return b;
}
}
package a;
import b.*;
public class A {
public void aa(B b) {}
}
package b;
public class B {}
import a.A;
import c.C;
public class Test {
public static void main(String[] args) {
A a = new A();
C c = new C();
a.aa(c.cc());
System.out.print("Test");
}
}
You need to import only the types you mention explicitly in the source code. When you call the
ccmethod, it is already clear to the compiler which type is the return value. Imports are there only to disambiguate the mention ofBinto the fully qualified type nameb.B.And no, this has nothing to do with dependency injection. In that phrase, “dependency” means a runtime dependency of an object to another object and has nothing to do with compile-time dependencies between Java types.