Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injection and inheritance

Tags:

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;
  1. How does @Inject know which one to instantiate ?
  2. I think this will throw an 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);}
}  
  1. What is the workaround?
like image 461
Charles Follet Avatar asked Apr 15 '16 13:04

Charles Follet


People also ask

What is the difference between dependency injection and inheritance?

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.

What is the dependency injection concept?

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 would you use a property injection?

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.


1 Answers

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 ;-)

like image 131
mtj Avatar answered Sep 28 '22 04:09

mtj