Section 12.3 Object Composition
It is time to discuss the second way of extending object behavior, and most of the time the preferred way, by so-called object composition.
Object composition is simply the process of one object using other objects to get its work done. We extend the object’s abilities by having it call methods of other objects. In an object composition setting we have two (or more) objects, from two different classes, and one of the objects uses the other.
Let’s see how this looks like for our courses and grades. We will once again have a
Course
class, but it will no longer extend the Grade
class. Instead, one of the fields of Course
will be Grade
:public class Course {
String prefix;
int number;
Grade grade;
Course(String prefix, int number, String letterGrade) {
this.prefix = prefix;
this.number = number;
this.grade = new Grade(letterGrade);
}
}
So a course simply has a
grade
property. In this example we created a new Grade
object based on the letterGrade
string they provided. We could also have had a constructor that takes a Grade
object instead:Course(String prefix, int number, Grade grade) {
this.prefix = prefix;
this.number = number;
this.grade = grade;
}
The relevant and important question is who should be responsible for creating
Grade
objects. And that’s a topic for another time.For now the important thing is that we can no longer directly call
course.getCredits()
, as Course
is not a Grade
object any more. We can still do course.grade.getCredits()
, we have to reach into the grade
field to find the Grade
object.So, we have "extended" the behavior of
Grade
objects by having another object that uses them to do things. This is very much in line with our earlier philosophy of "getting things done by having objects talk to each other".