abstract class Vehicle
{
void collide(Vehicle v){}
}
class Car extends Vehicle
{
@Override
void collide(Vehicle v){super.collide(v);}
}
class Truck extends Vehicle
{
@Override
void collide(Vehicle v){super.collide(v);}
}
If I do :
@Inject
Vehicle vehicle;
@Inject
know which one to instantiate ? AmbiguousResolutionException
, am I wrong? I would like to do this to avoid this problem and also specialize the parameters but it's not allowed, and I understand why.
class Car extends Vehicle
{
@Override
void collide(Car v){super.collide(v);}
}
class Truck extends Vehicle
{
@Override
void collide(Truck v){super.collide(v);}
}
One criticism of inheritance is that it tightly couples parent class with child class. It is harder to reuse the code and write unit tests. That's why most developers prefer dependency injection as a way to reuse code. Dependency injection is a way to inject dependencies into a class for use in its methods.
In object-oriented programming (OOP) software design, dependency injection (DI) is the process of supplying a resource that a given piece of code requires. The required resource, which is often a component of the application itself, is called a dependency.
When should I use property injection? You should use property injection in case the dependency is truly optional, when you have a Local Default, or when your object graph contains a cyclic dependency.
Second answer to your edited post (as you go into a totally different problem domain here):
For the specialization of parameters, you only have the possibility to parameterize the class itself, along the lines of:
abstract class Vehicle<T> { // T is the "collision partner class"
abstract void collide(T v);
}
class Car extends Vehicle<Car> {
@Override
void collide(Car v) { ... }
}
You can then inject a specialized type:
@Inject Vehicle<Car> thisIsACar;
Nevertheless, judging from your example, this is probably not what you want ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With