CPSC 210
C8:
Reflexive Relationships
🦵
🔨
Learning Goals
- Understand and implement reflexive relationships
Reflexive Relationships
- Also called bi-directional relationships
- Types know of each other and changes in one type must be reflected in the other
- Three general types: One to One, Many to One, Many to Many
0,1
0,*
public class Book {
private List<Review> reviews;
// ...
}
public class Review {
private Book book;
// ...
}
Bi-Directional (2)
public class Book {
// ...
private List<Review> reviews;
public void addReview(Review review) {
}
}
public class Review {
// ...
private Book book;
// REQUIRES: no book has yet been set
public void setBook(Book book) {
}
}
- Methods affecting the relationship must call associated method in the other class passing this
- To guard against infinite sequences, we check if the work has already been done in both
if (!this.reviews.contains(review)) {
this.reviews.add(review);
review.setBook(this);
}
if (this.book != book) {
this.book = book;
book.addReview(this);
}
Lecture Ticket
public void addIngredient(Ingredient ingredient) {
if (!this.ingredients.contains(ingredient)) {
ingredients.add(ingredient);
ingredient.addRecipe(this);
}
}
- Call method in the other class passing this
- Guard against infinite sequences
public void addIngredient(Ingredient ingredient) {
}
Lecture Lab
Don't miss Part 2!
C8: Reflexive Relationships
The End - Thank You!
CPSC210 - C8 Reflexive Relationships
By Steven Wolfman
CPSC210 - C8 Reflexive Relationships
- 210