Junior — Middle
Could you give an example of a situation where one object is related to multiple other objects?
sobes.tech AI
Answer from AI
An example of a situation where one object is related to multiple other objects is common in Java when modeling relationships between entities.
For example, a Student class can be associated with multiple Course objects, as a student may attend several courses:
import java.util.List;
public class Student {
private String name;
private List<Course> courses; // one-to-many relationship
public Student(String name, List<Course> courses) {
this.name = name;
this.courses = courses;
}
// getters and setters
}
public class Course {
private String title;
public Course(String title) {
this.title = title;
}
// getters and setters
}
Here, the Student object contains a list of courses, meaning it is related to multiple Course objects. This type of relationship is often called "one-to-many" and is widely used to model real-world relationships between objects.