CPSC 210

C8:
Reflexive Relationships

Learning Goals

  • Understand and implement reflexive relationships

Lecture Ticket

public void addIngredient(Ingredient ingredient) {
  if (!this.ingredients.contains(ingredient)) {
    ingredients.add(ingredient);
    ingredient.addRecipe(this);
  } 
}

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

Lecture Lab

C8: Reflexive Relationships

The End - Thank You!

CPSC210 - C8 Reflexive Relationships

By Felix Grund

CPSC210 - C8 Reflexive Relationships

  • 1,179