CPSC 210

C8:
Reflexive Relationships

Recap: Auto-generated equals method

  • Let's assume we have a class Instructor with a field name and:
    • we want to consider two instructor objects equal if they have the same name
@Override
public boolean equals(Object obj) {
  if (this == obj) 
  	return true;
  if (obj == null )
  	return false;
  if (getClass() != obj.getClass())
	return false

  Instructor other = (Instructor) obj;
  
  if (name != other.name )
  	return false
  return true
}

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

Lecture Ticket

Lecture Ticket

Lecture Lab

Lecture Lab

C8: Reflexive Relationships

The End - Thank You!

Copy of CPSC210 - C8 Reflexive Relationships

By firas_moosvi

Copy of CPSC210 - C8 Reflexive Relationships

  • 126