This is a rephrased question of one I asked previousy, but which wasn't well formulated and contained a few errors (incl. the answer I referred to, sorry about that) so I try again, in the hope that this question makes more sense.
I got confused over one of the answers in the following thread and I'm referring to the code snippet in the third answer (currently ca 117 upvotes):
Prefer composition over inheritance?
The answer illustrates composition using dependency injection see code snippet there).
Edit: repeated below:
class Person {
String Title;
String Name;
Int Age;
public Person(String title, String name, String age) {
this.Title = title;
this.Name = name;
this.Age = age;
}
}
class Employee {
Int Salary;
private Person person;
public Employee(Person p, Int salary) {
this.person = p;
this.Salary = salary;
}
}
Person johnny = new Person ("Mr.", "John", 25);
Employee john = new Employee (johnny, 50000);
What confuses me is that at school, we learned about:
- Direct association (not relevant for this question);
- Aggregation: weak relationship -> has-a-relationship;
- Composition: strong relationship -> ownership where one can't live without the other.
Examples given at school implied DI to be a part of aggregation, because it indicates a weak relationship.
Opposite to composition, where the examples indicate that ClassB is instantiated either in the constructor of classA, or by a setter of classA. ClassA is herewith explicitly responsible for the creation of classB (otherwise classB cannot exist).
The example given was a Person class where the Heart class was instantiated in the constructor of the Person class.
Is the assumption correct that dependency injection implies aggregation, or could one also have DI with composition?